Vasileios Tsakalis
Vasileios Tsakalis

Reputation: 1211

Add class with numbers to each li elements, jquery

Add class with numbers to each li elements, jquery.

Here is a sample of my code:

$('li').each(function(i) {

$(this).addClass(i);

});

There is a way to add class only with numbers, i know i am able to add class with this way $(this).addClass('something'+i); but instead i want only with numbers like:

<li class='1'></li>

Thank you!

Upvotes: 1

Views: 6167

Answers (4)

Noruzzaman
Noruzzaman

Reputation: 11

$('li').each(function(i) {
  $(this).addClass('class_name_'+i);
  i++;
});

Upvotes: 0

Umesh Warcholyk
Umesh Warcholyk

Reputation: 1

$('li').each(function(i) {
 $(this).attr('class','section-'+i);
 i++;
});

Upvotes: 0

hakazvaka
hakazvaka

Reputation: 733

Instead od $(this).addClass(i); try using $(this).addClass(i.toString());

But, having numbers as class names will get you into trouble... I just demonstrated how you can do this with jQuery.

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

Classname must begin with a letter. Numbers as class name are illegal in the CSS grammar.

See this

You can use the below hack to add the class number but you can not set the css for such class names:

$('li').each(function(i) {
 $(this).attr('class',i);
});

Demo

Upvotes: 0

Related Questions