JavaScript and getElementById for multiple elements with the same ID

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

I know this is an old question and that an HTML page with multiple identical 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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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:

https://stackoverflow.com/questions/3434278/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.

Solution 9 - Javascript

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.

Solution 10 - Javascript

This is my solution:

<script type="text/javascript">
    $(document).ready(function () {
       document.getElementsByName("mail")[0].value = "ex_mail1";
       document.getElementsByName("mail")[1].value = "ex_mail2";
    });
</script>

Or you can use for-loop for that.

Solution 11 - Javascript

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

Solution 12 - Javascript

we can use document.forms[0].Controlid

Solution 13 - Javascript

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajan PView Question on Stackoverflow
Solution 1 - JavascriptOdedView Answer on Stackoverflow
Solution 2 - JavascriptBrad BamfordView Answer on Stackoverflow
Solution 3 - JavascriptPaul ButcherView Answer on Stackoverflow
Solution 4 - JavascriptcprcrackView Answer on Stackoverflow
Solution 5 - JavascriptDelan AzabaniView Answer on Stackoverflow
Solution 6 - Javascriptremi bourgarelView Answer on Stackoverflow
Solution 7 - JavascriptChristian LæirbagView Answer on Stackoverflow
Solution 8 - JavascriptIsmael CovarrubiasView Answer on Stackoverflow
Solution 9 - JavascriptMoin ZamanView Answer on Stackoverflow
Solution 10 - JavascriptKhánh PlutoView Answer on Stackoverflow
Solution 11 - Javascriptyasin ullahView Answer on Stackoverflow
Solution 12 - JavascriptBala KumarView Answer on Stackoverflow
Solution 13 - JavascriptRajol KochlashviliView Answer on Stackoverflow