Can first descendent be selected directly?
- by Ben Huh
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.