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>
Definition and Usage. The :first-child selector selects all elements that are the first child of their parent. Tip: Use the :last-child selector to select elements that are the last child of their parent.
The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.
grab the second child: $(t). children(). eq(1);
Use :first selector:
$('#resultsBox li:first').addClass('aaaa');
and for the third element selection, you can use each() method: Here is jsFiddle.
$('ul li').each(function(i) {
if ( i === 2 ) {
$(this).addClass('aaaa');
}
});
or you can do this with eq method like Jamiec & MrThys mentioned: but each method will be much usefull when things getting complicated.
$('#resultsBox li').eq(2).addClass('aaaa');
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