Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

behavior of javascript getElementById() when there are elements with duplicate IDs in HTML DOM?

Tags:

javascript

Can someone shed some light on the behavior of javascript getElementById() when there are elements with duplicate IDs in HTML DOM??

like image 746
Arjun Avatar asked Jul 17 '12 18:07

Arjun


People also ask

What is the use of getElementById () JavaScript HTML method?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.

Can you have duplicate IDs in HTML?

Duplicate IDs are common validation errors that may break the accessibility of labels, e.g., form fields, table header cells. To fix the problem, change an ID value if it is used more than once to be sure each is unique.

Which object does the method getElementById () belong to?

The method getElementById can be called only on document object. It looks for the given id in the whole document.

Can you have multiple IDs in JavaScript?

No it is not possible. ID always refer to uniqueness.


1 Answers

While there is no standard behavior defined, typically it will return the first element found.

Demo: http://jsfiddle.net/ruNKK/

like image 80
Ayman Safadi Avatar answered Sep 18 '22 10:09

Ayman Safadi