Skip to content Skip to sidebar Skip to footer

Two Elements With The Same Id, Want To Select One Contained In A Specific Div

I have something like this
I want to

Solution 1:

Having more than one element with the same idis invalid. So the correct solution here is: Fix that. (Typically using a class instead, but there are other options.)

That said, you may be able to use querySelector for this:

var elm = document.querySelector("#container1 #item0");

But as the structure is invalid, results would vary from implementation to implementation, and I wouldn't be surprised if many (or even most) returned null.

Again with the caveat that the real solution is to fix the invalid duplicate id, it may be more reliable than the above to use getElementById to get the container1 element and then loop through its child nodes looking for one with id == "item0".

Solution 2:

Having the same id attribute on two elements is a syntax error, so you should fix the markup. Browser behavior is undefined when the rule is violated.

If you cannot fix the error, for some odd reason, you can still find the element with id=container1, if that id attribute is unique, and then select its first child element, if the markup is exactly as given in the question.

Solution 3:

I know you haven't tagged this with jQuery - but I think it could be a solution. So what about giving every div a class, and then run an each-loop with jQuery?

<div id='container0' class='container'>
    <input id='item0' class='item'>
</div>


<div id='container1' class='container'>
    <input id='item0' class='item'>
</div>

Then I think an each loop could handle it like this:

$('div.container').each(function(key, value) { 
    var elmid = $("#"+key + " div.item).attr('id');
    var containerid = $(this).attr('id');

    var newelmid = elmid.replace('item','');    
    var newcontainerid = elmid.replace('container',''); 

    if(newelmid != newcontainerid)
    {
        $("#"+elmid).attr('id', 'item'+newcontainerid);
    }

});

Let me know if that is anyway near what you want to do :)

Solution 4:

As the others mentioned, you cannot have the same id for multiple elements. You can, however, have the same name. After you correct the syntax issue of multiple ids to make each if unique, you can select the second input element based on the container it is in. I would use jQuery for this.

For example (please note that I am not at my computer - I'm on my phone, so there may be some slight syntax changes required):

$("#container1 > input[name='item']").attr('id', 'item1')

For jQuery selectors, look here: http://api.jquery.com/category/selectors/

For changing attributes, look here: http://api.jquery.com/attr/

Post a Comment for "Two Elements With The Same Id, Want To Select One Contained In A Specific Div"