Search code examples
javascriptjqueryclasselementchildren

Jquery - Get xth element


For example, I have a div with an id (lets say "the_div"). This div contains an unordered list, and this list has 5 items in it.

How would I add a class to the third list item, without any of the list items having a class attached to them?

Edit: Even better, how would I change the list item text to equal what number element it was?

Thanks.


Solution

  • For your first problem, you can use eq, which is 0 based:

    $('ul li', '#thediv').eq(2).addClass('whatever'); // add class to 3rd item
    

    For your second problem, you can use each to iterate through all the list items. The callback function passes an argument containing the index of the current element in the set:

    $('ul li', '#thediv').each(function(i) {
        $(this).text(i); // update each list item with its index, 0 based.
    });