Accessing multiple HTML ID selectors and changing innerHTML of them.
This is part of a more complex code (relating to a multi-tabbed calculator).
What I am ultimately doing is compiling all the IDs that need a formatting adjusting and wanting to utilize a function to make the necessary adjustments (for example adding a $ or a % or decimals, etc), but I was having trouble with it so I condensed it down to bare bones to show for example.
Ironically I thought this would be the easiest for me to do, but all the other code I have written I had a much easier time handling. These IDs hold values in their actual state, which I have being pulled from form data inputs and calculations handled in other functions... but I wanted this to happen last (so to not interfere with the calculations).
I have two examples above the code I'm focused on. I want to utilize an array of all the IDs and select it in the function. Both work on their own, but the code at line 14 -> 17 doesn't work. Can someone tell me why?
In this example code, the expected behavior is both IDs adjusting the innerHTML to say hiho.
The error in the console just leaves me asking "why?" How do I get this to work as expected?
https://jsfiddle.net/cotm2xhs/
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
7 Replies
you need to put the
e
there not the whole array 😉 document.getElementById(e).innerHTML = "hiho"
or use an arrow function
ohh I didn't realize I wasn't iterating through
Thank you!!
alternatively, you can use
document.querySelectorAll()
with comma-separated ids
you can do this too:
not because it accepts an array, but because ids
will be converted to a string by calling the .toString()
method implicitly, which will use the method .join(',')
That's hacky... I would go with Mannix's solution or (if possible) add a class or a
data-*
attribute on the elements that needs formatting and do a single query selector on that class or attribute instead. It makes it so you don't need to maintain a list of stuff to format, but that might not be an issue for you (if you need to format every single element you deal with for example)i very strongly disagree about being hacky
if you're explicit with the join, then it's fine
and the css selector is perfectly valid
however, a class or data attribute is a much better idea
If you are explicit sure...
yeah, but classes are better