willbeing
willbeing

Reputation: 425

Can function arguments be passed into a string?

I'm making a calculator table with javascript, and I'm writing document.getElementById('x').innerHTML all the time. Can I write a function to replace this code? For example:

function select (a) {
  return document.getElementById(${a}).innerHTML;
}

The trouble I see is if I used template literals within getElementById, I can't add the quotes necessary to define the string as a string.

To put it back into context, I have many cells in a table each with different Ids. In order to allow js to update each cell, I've had to repeatedly write: document.getElementById('x').innerHTML. This had me wonder, can I just write a little function that would let me skip this extra typing? Can a function take an argument and return it with quotes around it?

Upvotes: 0

Views: 62

Answers (2)

PaulProgrammer
PaulProgrammer

Reputation: 17630

Just

var select = function(a) {
  return document.getElementById(a).innerHTML;
}
var ham = select('thing');

is good enough. The system already knows there's a string there, because that's the type it is when you call the select() function.


If you're trying to make for less typing while assigning a value to the innerHTML, you have to do that within the function body as well. Why? Because once you return the innerHTML string property from the function it's an immutable value, similar to saying 'a' = 'b'.

Here's what that assignment function might look like:

var assign = function( target, value) {
    document.getElementById(target).innerHTML = value;
}
assign('capitalGain', '$' + currency(initialGain));

Upvotes: 3

Jack Bashford
Jack Bashford

Reputation: 44105

You don't need template literals for a task this simple:

function select(a) {
    return document.getElementById(a).innerHTML;
}

Or if you must:

function select(a) {
    return document.getElementById(`${a}`).innerHTML;
}

And now Chrome supports a jQuery-like syntax - so in new versions of Chrome, this will also work.

function select(a) {
    return $(`#${a}`)[0].innerHTML;
}

Or the more verbose and understandable version:

function select(a) {
    let str = "#" + a;
    let [elem] = $(str);
    return elem.innerHTML;
}

And one more - in contrast to the verbose one, this one is quite unreadable and bad practice.

const select = a => ([{ innerHTML: b }] = $(`#${a}`), b);

Upvotes: 1

Related Questions