JavaScript and getElementById for multiple elements with the same ID

How can I get a collection of elements by specifying their id attribute? I want to get the name of all the tags which have the same id in the html.

I want to use ONLY getElementById() to get an array of elements. How can I do this?


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.


I know this is an old question and that an HTML page with multiple IDs is invalid. However, I ran into this issues while needing to scrape and reformat someone else's API's HTML documentation that contained duplicate IDs (invalid HTML).

So for anyone else, here is the code I used to work around the issue using querySelectorAll:

var elms = document.querySelectorAll("[id='duplicateID']");

for(var i = 0; i < elms.length; i++) 
  elms[i].style.display='none'; // <-- whatever you need to do here.

Why you would want to do this is beyond me, since id is supposed to be unique in a document. However, browsers tend to be quite lax on this, so if you really must use getElementById for this purpose, you can do it like this:

function whywouldyoudothis() {
    var n = document.getElementById("non-unique-id");
    var a = [];
    var i;
    while(n) {
        a.push(n);
        n.id = "a-different-id";
        n = document.getElementById("non-unique-id");
    }

    for(i = 0;i < a.length; ++i) {
        a[i].id = "non-unique-id";      
    }
    return a;
}

However, this is silly, and I wouldn't trust this to work on all browsers forever. Although the HTML DOM spec defines id as readwrite, a validating browser will complain if faced with more than one element with the same id.

EDIT: Given a valid document, the same effect could be achieved thus:

function getElementsById(id) {
  return [document.getElementById(id)];
}

document.querySelectorAll("#yourId"); returns all elements whose id is yourId