Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 out?

Note: I know duplicate id's is against standards but I'm using the fancybox modal popup and it duplicates specified content on your page for the content of the popup. If anyone knows a way around this (maybe I'm using fancybox wrong) please let me know.

like image 410
Matt Avatar asked Jun 27 '09 23:06

Matt


2 Answers

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).

like image 173
karim79 Avatar answered Nov 02 '22 23:11

karim79


"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.

like image 32
Matthew Flaschen Avatar answered Nov 02 '22 23:11

Matthew Flaschen