<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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With