Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript and getElementById for multiple elements with the same ID

Tags:

javascript

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?

like image 829
Rajan P Avatar asked Aug 31 '10 08:08

Rajan P


People also ask

Can I get multiple elements by ID JavaScript?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.

Can I have multiple elements with the same ID?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

What will the JavaScript ID selector return in case there are multiple elements with the same ID?

The id must be unique. There can be only one element in the document with the given id . If there are multiple elements with the same id , then the behavior of methods that use it is unpredictable, e.g. document. getElementById may return any of such elements at random.

How do I use multiple documents in getElementById?

You could use document. querySelectorAll() that allows you to specify multiple ids in a CSS selector string . You could put a common class names on all those nodes and use document. getElementsByClassName() with a single class name.


1 Answers

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.

like image 161
Oded Avatar answered Oct 04 '22 19:10

Oded