abhis abhis - 4 months ago 36
jQuery Question

How to apply active class for first list item using jquery

<div class="accordion">
<ul class="navigation">
<li>Lorem</li>
<li>Ipsum</li>
<li>Donor</li>
</ul>
<ul class="navigation">
<li>Test</li>
<li>Demo</li>
<li>Donor</li>
</ul>
</div>


How can we apply a class which is 'active' to first 'li' (ie;Lorem) only, not for all first 'li' under 'ul' using jquery.
I would like to get output as

<div class="accordion">
<ul class="navigation">
<li class="active">Lorem</li>
<li>Ipsum</li>
<li>Donor</li>
</ul>
<ul class="navigation">
<li>Test</li>
<li>Demo</li>
<li>Donor</li>
</ul>
</div>

Answer

You can use :first (as opposed to :first-child which would get the first per-<ul>), and .addClass() like this:

$(".accordion li:first").addClass("active");

Or .first(), which is an alias for .eq(0) or .slice(0,1) even, like this:

$(".accordion li").first().addClass("active");
//or
$(".accordion li").eq(0).addClass("active");
//or
$(".accordion li:eq(0)").addClass("active");
//or
$(".accordion li").slice(0,1).addClass("active");

There are a few ways to go about it...though I prefer :first or .first() for clarity.