Search code examples
jqueryjquery-selectors

How to select the closest descendant using jquery or selector?


I want to get the descendant of a node that match class="foo".
The problem is : I don't know how deep this descendant will be.
I know I could get the immediate child using >
Or if I knew how deep it is, I could use multiple > > > >
I could just use class="foo" but then I'll get descendant of my target that also match class="foo".

Is div.class="foo":first-child the solution ?

div id="im_here"
  div id="child"
    ......
         div class="foo"              <= I want this
           ......
                div class="foo"       <= not that
                ......
                      div class="foo" <= not that
                      ......

Solution

  • You can use jQuery's :first selector in conjunction with .find():

    $('#im_here').find('.foo:first')