Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class to first child with jQuery?

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>
like image 267
lisovaccaro Avatar asked Aug 08 '12 07:08

lisovaccaro


People also ask

Is first child jQuery?

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.

What is addClass and removeClass in jQuery?

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.

How can I get second child in jQuery?

grab the second child: $(t). children(). eq(1);


1 Answers

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');
like image 143
Barlas Apaydin Avatar answered Sep 25 '22 18:09

Barlas Apaydin