Let say I have the following HTML elements:
<div id="id">
<div class="first">
<div class="second"></div>
</div>
</div>
I'm wondering why this doesn't work in jQuery:
$("#id.first.second").click( // do some stuff ...
I usually use something like the following which works fine, but today I just found out that the above example is not working.
// working example
$("#id .second").click( // do some stuff ...
Update: My question is why it is not working without spaces? Thanks!
The selector #id.first.second means "an element with the id value "id" which also has the classes first and second".
Your second selector #id .second (with the space before .second) means "an element with the id value "id" which has a descendant element with class second". It's a "descendant selector".
So if you want to specify each of the three levels, you'd do this:
$("#id .first .second").click(...
...which means "an element with the id value "id" which has a descendant element with the class first which, in turn, has a descendant element with class second".
Or alternately, you might do:
$("#id > .first > .second").click(...
...which means "an element with the id value "id" which has a direct child element with the class first which, in turn, has a direct child element with class second. It's a child selector (actually two of them).
Or, of course, some combination of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With