How to add class to first child with jQuery?

Viewed 79395

How do I add a class an element on a container with a certain index?

I'm trying this right now which should affect the first element (doesn't work anyway)

$('#resultsBox li:first-child').addClass('aaaa');

But I want to be able to change class of any element in it's container having the index.

EG if I want to modify element with index = 2.

<div id="resultsBox">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>

Should become:

<div id="resultsBox">
<ul>
<li></li> // Index 0
<li></li> // Index 1
<li class="selected"></li> // Index 2
</ul>
</div>
5 Answers

For select ul

$("#resultsBox ul").first().addClass( "aaaa" );

For select first li

$("#resultsBox ul li").first().addClass( "aaaa" );
Related