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-c
Solution 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');
Solution 2:
The cleanest way of achieving this would be:
$('#resultsBox li').eq(2).addClass('selected');
Documentation on the .eq method can be found here: http://api.jquery.com/eq/
Solution 3:
Use the :first selector, or the :nth-child selector. I mention the :nth-child selector simply in case you want to add classes to anything other than the first. You can also use :nth-child in plain CSS without javascript if you want
$("#resultBox li:nth-child(1)").addClass('aaa');
Solution 4:
For select ul
$("#resultsBox ul").first().addClass( "aaaa" );
For select first li
$("#resultsBox ul li").first().addClass( "aaaa" );
Solution 5:
$('#resultsBox li:eq(2)').addClass('aaaa');
or eq function
$('#resultsBox li').eq(2).addClass('aaaa');
Post a Comment for "How To Add Class To First Child With Jquery?"