matt
matt

Reputation: 2352

jquery modify a particular li element only knowing its position in the list

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

Answers (5)

paulslater19
paulslater19

Reputation: 5917

Or inline:

$("ul li:eq(2)").html("Add some content")

Source: http://api.jquery.com/eq-selector/

Upvotes: 1

inhan
inhan

Reputation: 7470

Any of the following will return you that 2nd <li> element.

  1. $('ul li:eq(3)')
  2. $('ul>li:eq(3)')
  3. $('ul li').eq(3)
  4. $('ul>li').eq(3)
  5. $('ul li').filter(function() { return $(this).index() == 3; })
  6. $('ul>li').filter(function() { return $(this).index() == 3; })

Upvotes: 0

Codegiant
Codegiant

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

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

Use .eq(), which takes a specified index (0-based) as an argument:

$("ul li").eq(2).addClass("yourClass");

DEMO.

Upvotes: 3

askmike
askmike

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

Related Questions