Take the 2-minute tour ×

I want JavaScript to output a string in every matching location using InnerHTML, but it's only handling the first one. It works perfectly fine the first encounter, but ignores the others.

I can resolve the matter by doing this:

 // etc.

But that's insanely redundant.
Is .getElementById meant to only handle the first matching tag?

share|improve this question
Link bt @darryn.ten is good, remember id's are supposed to be unique! –  Andy Davies Mar 6 '12 at 10:41
add comment

1 Answer

up vote 0 down vote accepted

Is .getElementById meant to only handle the first matching tag?

Yes, it is supposed to return (at most) just the one element that has the specified id (the exact id, not some prefix or regular expression match).

If you want to match many elements, you should consider giving them a common class.

Or maybe they have a common ancestor and path, so you could select them with something like

document.querySelectorAll('#commonParentId span')

(all spans within the element with the id commonParentId, supported by IE8 and above).

share|improve this answer
What is the $ representing? –  squint Mar 1 '12 at 5:35
@Thio, please don't just randomly throw in a reference to a piece of jQuery code when the question doesn't ask for jQuery and you don't even mention that it's jQuery. The general convention here is that if the question doesn't mention jQuery, include jQuery code examples or include the tag for jQuery, then they aren't asking for jQuery. –  jfriend00 Mar 1 '12 at 5:38
add comment

Your Answer


