Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: addClass 1,2,3 etc. auto to a list

is it possible, to add auto numeric classes to a list by using jquery?

html:

<ul id="list">
 <li>Element 1</li>
 <li>Element 2</li>
 <li>Element 3</li>
 <li>Element 4</li>
 <li>Element 5</li>
</ul>

i want to get something like this:

<ul id="list">
 <li class="1">Element 1</li>
 <li class="2">Element 2</li>
 <li class="3">Element 3</li>
 <li class="4">Element 4</li>
 <li class="5">Element 5</li>
</ul>

hope there is a solution available :-)


Edit

ok, mhhm but my list has not always a number at the end. so what's about a classname combination, like "item + number" ? is something like this possible?

<ul id="list">
 <li class="item1">Element x</li>
 <li class="item2">Element c</li>
 <li class="item3">Element a</li>
 <li class="item4">Element d</li>
 <li class="item5">Element f</li>
</ul>
like image 655
Svensson Avatar asked Apr 15 '10 14:04

Svensson


1 Answers

   $("#list li").each(function(i) {
     this.addClass("item"+(i+1));
    });

Here it is in action

http://jsbin.com/ocake

Update per comments, as in example link this works :

$(document).ready(function() {
        $("#list li").each(function(i) {
        $(this).addClass("item" + (i+1));
        });
      });

But I think initial code should work by adding :

this = $(this);

But not sure.

like image 87
ant Avatar answered Oct 20 '22 03:10

ant