Skip to content Skip to sidebar Skip to footer

Do Duplicate ID Values Screw Up JQuery Selectors?

If I had two divs, both with id='myDiv', would $('#myDiv').fadeOut(); fade both divs out? Or would it fade only the first/second? Or none at all? How do I change which one it fades

Solution 1:

Element IDs are supposed to be unique. Having multiple DIVs of the same ID would be incorrect and unpredictable, and defies the purpose of the ID. If you did this:

$('.myDiv').fadeOut();

That would fade both of them out, assuming you give them a class of myDiv and unique IDs (or none at all).


Solution 2:

"Note: I know duplicate id's is against standards"

Then don't do it. You have already figured out two problems. It violates standards, and it interferes with jQuery's (and indeed the regular DOM's) selection mechanism. There will probably be more issues in the future.

Quite possibly, you are using fancybox wrong, in which case I hope someone familiar with it helps you. Or worse, if the script itself is flawed, you shouldn't use it.


Solution 3:

jQuery matches exactly one element when querying for an ID. An array of at most one Element object will be returned by $("#foo").get(). See the jQuery documentation for more information, or try it yourself.

$(function() {
    alert($("#foo").length);
});

Solution 4:

Since $('#myDiv') will only return the first div with that ID, you'll have to find all elements with that ID using this trick:

$('[id=myDiv]');

So, for your case, to apply the fadeOut to all of those divs:

$('[id=myDiv]').fadeOut();

And if you want to make sure your page doesn't have this ID twice then you can remove the extra ones by doing this:

$('[id=myDiv]:gt(0)').remove();

Solution 5:

You can also go the route of using find(). find will return all the elements with that ID, and you can limit the scope to a particular parent if needed try something like $(document).find('#myDiv').fadeOut();

or

$('.parentElement').find('#myDiv').fadeOut();

Post a Comment for "Do Duplicate ID Values Screw Up JQuery Selectors?"