2

Using jQuery, is it possible to assign a class to an object based on its index?

For example, if I have an ul with five list items, how would I assign the class "0" to the first item, "1" to the second item, "2" to the third, item and so on?

This was my first attempt:

$('ul.nav li').each(function(index){
  $(this).addClass(index);
});
1
  • 2
    Your real problem is that classes can't start with numbers. Other than that this technique is fine. Append some text on the front of those classnames and you're good to go. Commented May 18, 2012 at 16:38

4 Answers 4

9

But avoid to start class or id with number;

$('ul.nav li').each(function(index){
  $(this).addClass('at_'+ index);
});
Sign up to request clarification or add additional context in comments.

1 Comment

This solution I'm guessing is a little cleaner since the each function is passed in the index, there is no reason to have to reference $(this) again.
7

Bearing in mind that classes can't start with numbers, something like this should do:

$('ul.nav li').each(function(){
  $(this).addClass("index_"+$(this).index);
});

1 Comment

No problem. I'd have posted it with my answer if you hadn't beaten me to it. :)
1

Class names should not start with numbers. Instead do something like

$('ul.nav li').each(function(index){
  $(this).addClass("class_"+index);
});

Comments

0

It is working for me with this:

$('ul.nav li').each(function(index){
  $(this).attr('class', 'class'+index);
});​

http://jsfiddle.net/8JCXD/7/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.