Skip to content Skip to sidebar Skip to footer

Dealing With Two Elements With Same Id In Javascript

I know that IDs should be unique, however I have to deal with a page that has two elements with the exact same ID, when I try to get the element by ID it only selects the first one

Solution 1:

var bothElements = document.querySelectorAll("[id='Edit']");

you can then access the second one with:

bothElements[1].

Solution 2:

I know that IDs should be unique, however, I have to deal with a page that has two elements with the exact same ID

As you've stated it should be unique hence if you have more than one id attribute with the same name then that's not valid HTML.

How can I access the second element with the exact same ID as the first in JavaScript?

wouldn't it be easier to use getElementsByClassName since having two id attributes with the same name is invalid HTML?.

with that in mind, you can use getElementsByClassName.That may be more suited to your requirements.

Example:

var x = document.getElementsByClassName("Design_01"); // x is an arrayvar firstElement = x[0]; // get first elementvar secondElement = x[1]; // get second element

Relevant Readings:

Solution 3:

You can use the class selector to select all of them and then nominate the one you want.

var inputs = document.getElementsByClassName('Design_01');
var requiredInput = inputs[1];

Solution 4:

While these techniques may very well work, I'd advise caution if you are building a solution that might have two or more of the same ids on a page, as these techniques may be unreliable. In my experience, invalid HTML will almost certainly cause problems elsewhere.

See the spec: https://www.w3.org/TR/html5/dom.html#the-id-attribute

The id attribute specifies its element's unique identifier (ID).

While you may get this to work in your environment, different browsers, implementations and frameworks can handle it differently. Browser updates might break your solution without warning.

I strongly recommend you use a class or resolve the issue with the HTML.

Post a Comment for "Dealing With Two Elements With Same Id In Javascript"