Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 950
Aadi Avatar asked Nov 02 '10 11:11

Aadi


1 Answers

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.

like image 65
Nick Craver Avatar answered Oct 08 '22 18:10

Nick Craver