JavaScript and getElementById for multiple elements with the same ID

The HTML spec requires the id attribute to be unique in a page:

[T]he id attribute value must be unique amongst all the IDs in the element’s tree

If you have several elements with the same ID, your HTML is not valid.

So, document.getElementById should only ever return one element. You can’t make it return multiple elements.

There are a couple of related functions that will return a list of elements: getElementsByName or getElementsByClassName that may be more suited to your requirements.

Leave a Comment