views:

390

answers:

2

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.

A: 

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.
});
Paolo Bergantino
I would say .text(i) not .html(i). +1 though.
strager
Well, jQuery obviously figures it out, but point taken. Edited.
Paolo Bergantino
Mmm. Reading the documentation, the only difference between html() and text() is that text() escapes HTML. That obviously doesn't matter here. Is there some "best practice" as to when to use one or the other? I feel like html() is probably for divs mostly, but this is just a hunch.
Paolo Bergantino
+3  A: 

Or...

$('#the_div ul li:eq(2)').addClass('className');

You can combine the selectors together - if you prefer :)

markt
I think that is purely a matter of preference. I find those long selector strings unsightly and separating them shows intent more clearly and is faster.
Paolo Bergantino
Preference yep.. I find they are generally somewhat similar to CSS, so I prefer that consistency.. ;)
markt
+1, I think this solution is much nicer. Less noise.
cdmckay