Reputation: 2352
I have a simple list:
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
I need to modify one of the li elements, all I know is it's position in the list, for example 2 which would be the 3rd li element). How can I add a class to it by only knowing that?
Upvotes: 1
Views: 459
Reputation: 5917
Or inline:
$("ul li:eq(2)").html("Add some content")
Source: http://api.jquery.com/eq-selector/
Upvotes: 1
Reputation: 7470
Any of the following will return you that 2nd <li>
element.
$('ul li:eq(3)')
$('ul>li:eq(3)')
$('ul li').eq(3)
$('ul>li').eq(3)
$('ul li').filter(function() {
return $(this).index() == 3;
})
$('ul>li').filter(function() {
return $(this).index() == 3;
})
Upvotes: 0
Reputation: 2150
try this
HTML
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
</ul>
JS
$('ul').children().eq(2).addClass('newclass');
Upvotes: 0
Reputation: 91299
Use .eq()
, which takes a specified index (0-based) as an argument:
$("ul li").eq(2).addClass("yourClass");
DEMO.
Upvotes: 3
Reputation: 1960
You can use the .eq
function to specify wich index you want:
$('ul').children().eq(2)
will point to the third item (indexes start at 0, so 2 is the third)
Upvotes: 0