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>
Use :first selector:
and for the third element selection, you can use each() method:
Here is jsFiddle.
or you can do this with eq method like Jamiec & MrThys mentioned: but each method will be much usefull when things getting complicated.