[javascript] 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?

This question is related to javascript

The answer is


If you're using d3 for handling multiple objects with the same class / id

You can remove a subset of class elements by using d3.selectAll(".classname");

For example the donut graph here on http://medcorp.co.nz utilizes copies of an arc object with class name "arc" and there's a single line of d3, d3.selectAll(".arc").remove(); to remove all those objects;

using document.getElementById("arc").remove(); only removes a single element and would have to be called multiple times (as is with the suggestions above he creates a loop to remove the objects n times)


we can use document.forms[0].Controlid


You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.

Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.


Class is more than enough for refering anything you want, because it can have a naming with one of more words:

<input class="special use">
<input class="normal use">
<input class="no use">
<input class="special treatment">
<input class="normal treatment">
<input class="no special treatment">
<input class="use treatment">

that's the way you can apply different styles with css (and Bootstrap is the best example of it) and of course you may call

document.getElementsByClassName("special");
document.getElementsByClassName("use");
document.getElementsByClassName("treatment");
document.getElementsByClassName("no");
document.getElementsByClassName("normal");

and so on for any grouping you need.

Now, in the very last case you really want to group elements by id. You may use and refer to elements using a numerically similar, but not equal id:

<input id=1>
<input id="+1">
<input id="-1">
<input id="1 ">
<input id=" 1">
<input id="0x1">
<input id="1.">
<input id="1.0">
<input id="01.0">
<input id="001">

That way you can, knowing the numeric id, access and get an element by just adding extra non-invalidating numeric characters and calling a function to get (by parsing and so on) the original index from its legal string identifying value. It is useful for when you:

  • Have several rows with similar elements and want to handle its events coherently. No matter if you delete one or almost all of them. Since numeric reference is still present, you can then reuse them and reassign its deleted format.

  • Run out of class, name and tagname identifiers.

Although you can use spaces and other common signs even when it's a not a requirement strictly validated in browsers, it's not recommended to use them, specially if you are going to send that data in other formats like JSON. You may even handle such things with PHP, but this is a bad practice tending to filthy programming practices.


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)];
}

you can use document.document.querySelectorAll("#divId")


The HTML spec required the ID attribute to be unique in a page:

This attribute assigns a name to an element. This name must be unique in a document.

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

So, 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 an array of elements - getElementsByName, or getElementsByClassName that may be more suited to your requirements, though getElementsByClassName is new to HTML 5, which is still in draft.


As others have stated, you shouldn't have the same ID more than once in your HTML, however... elements with an ID are attached to the document object and to window on Internet Explorer. Refer to:

Do DOM tree elements with ids become global variables?

If more than one element with the same ID exists in your HTML, this property is attached as an array. I'm sorry, but I don't know where to look if this is the standard behavior or at least you get the same behavior between browsers, which I doubt.


It is illegal to have multiple elements with the same id. The id is used as an individual identifier. For groups of elements, use class, and getElementsByClassName instead.


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.

The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.


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