views:

44

answers:

3

Hi, Is there any ways to add different style class to all li in a ul tag using jquery/javascript/php. Consider I have a list as follows

<ul><li>a</li><li>b</li><li>c</li><li>d</li><li>e</li></ul>

I would like to add as follows

<ul><li class='cat1'>a</li><li class='cat2'>b</li><li class='cat3'>c</li><li class='cat4'>d</li><li class='cat5'>e</li></ul>
+3  A: 

If you want to set the class, the cheaper way to do it is by using .attr() and the index in its setter function, like this:

$("ul li").attr("class", function(i) {
  return "cat" + (i+1);
});

If you aren't setting it and just adding, use .addClass(function(i) instead of .attr("class", function(i).

Nick Craver
+1 Don't know why you got a downvote for this.
GenericTypeTea
@GenericTypeTea - Thanks :) I tried to clarify why I'm doing this as opposed to `.addClass()` (given the question), as there is a tremendous performance difference, hopefully that clarifies it a bit?
Nick Craver
+5  A: 

As simple as:

$('ul').children('li').addClass(function (i) {
    return 'cat' + (i+1);
});

http://api.jquery.com/addClass/

Matt
+1 best solution of those offered here. I didn't know `addClass()` can take a function argument, but this makes sense absolutely.
Tomalak
@Tomalak - If dealing with a large number of elements though and you're just *setting* the class (e.g. you *know* there aren't any previously), then it's far less efficient, so something to keep in mind when choosing.
Nick Craver
@Tomalak It's new in 1.4. A lot of the functions now accept function arguments
Yi Jiang
@Nick: Why is that? (primarily I was referring to explicitly calling `children()` instead of selecting `"ul li"` - specific and less error prone) -- @Yi: Ah I see, my knowledge obviously was from earlier versions. Thanks for the hint.
Tomalak
@Tomalak - For the selector bit you can do `ul > li` :) I was talking about the `addClass` part ;)
Nick Craver
@Nick: The `>` would be the same result, yes. Knowing it is one thing, thinking of it, another. :) I was referring to `addClass` as well - why would that be "far less" efficient in this context?
Tomalak
@Tomalak - `.addClass()` takes the existing `class` attribute, splits it, loops though, checking if it's set then combining and adding them back, `.attr()` just checks node type, node name (for special attributes) then calls `setAttribute`, much faster overall and *way* faster in browsers that inline the script (most tracing engines now).
Nick Craver
@Nick: Thanks, makes sense.
Tomalak
A: 
$('ul').children('li').each(function(i,v){
   $(this).addClass('cat'+(i+1));
});
jAndy