Adding a Class to First Child with jQuery (ACFCJ)

How to add class element to container with specific index?

I'm trying this now which should affect the first element (it doesn't work though).

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

But I want to be able to change the class of any element in its container that has an index.

For example, if I want to modify an element with index = 2.

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

It should be:

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

Solutip

Use the first selector:

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

and for the selection of the third element, you can use the method  each() in  jsFiddle .

$('ul li').each(function(i) {
    if ( i === 2 ) {
       $(this).addClass('aaaa');
    }
});

or you can do this with methods, examples like the ones Jamiec & MrThys mentioned: but any method will be very useful when things get complicated.

$('#resultsBox li').eq(2).addClass('aaaa');

Post a Comment

Previous Next

نموذج الاتصال