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);
});
But avoid to start class or id with number;
$('ul.nav li').each(function(index){
$(this).addClass('at_'+ index);
});
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);
});
Class names should not start with numbers. Instead do something like
$('ul.nav li').each(function(index){
$(this).addClass("class_"+index);
});
It is working for me with this:
$('ul.nav li').each(function(index){
$(this).attr('class', 'class'+index);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.