Search code examples
javascriptjqueryjquery-selectorstraversal

Can first descendent be selected directly?


I am currently using find() and first() method to select the first descendent element from each of the <div> elements that contains the parent class. But I find this quite cumbersome since find() method would produce a set of matched elements before the first element is being picked. The following is the skeleton of my code:

HTML

<div class=parent>
 <ul>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
 </ul>
</div>
<div class=parent>
 <ul>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
 </ul>
</div>
<div class=non-parent>
 <ul>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
 </ul>
</div>
<div class=parent>
 <ul>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
  <li>random characters</li>
 </ul>
</div>
// .....the list continues

Javascript

$('.parent').each(function() {
 $(this).find('ul li').first().css('color', 'red');
// do other stuff (on other elements) within each loop
});

I have seen people using $(".parent li:first") selector. But, because I am doing it in a loop, I am not sure how or whether if this could be done and would like some advice. Thanks.

Clarification:

I need to do other stuff on other elements not shown in the HTML within each loop. Thanks.


Solution

  • If you insist on both the outer loop and the :first selector, then use this:

    $('.parent').each(function() {
        $(this).find('li:first').css('color', 'red');
        // do other stuff within each loop
    });
    

    Note that the following will not work:

    $('.parent li:first').css('color', 'red');
    

    ....because it will simply select the first li descendant across all .parent elements.