Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery nested DOM selector

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!

like image 464
Mahdi Avatar asked Dec 27 '22 08:12

Mahdi


1 Answers

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.

like image 189
T.J. Crowder Avatar answered Jan 09 '23 19:01

T.J. Crowder