Can first descendent be selected directly?

Posted by Ben Huh on Stack Overflow See other posts from Stack Overflow or by Ben Huh
Published on 2012-06-30T03:10:10Z Indexed on 2012/06/30 3:15 UTC
Read the original article Hit count: 165

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

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery