Tomkay
Tomkay

Reputation: 5160

JQuery - Number every li

I do not know much about arrays and numbering objects. I hope you understand what I mean with "numbering every li". So the first li gets the class "0", the second li gets the class "1", and so on.

Html

<div id="imtheking">
<ul>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
</ul>
</div>

Pseudo Javascript (Jquery)

$('#imtheking ul > li').number(starting from: '0');

Result HTML

<div id="imtheking">
<ul>
<li class="0">List Item</li>
<li class="1">List Item</li>
<li class="2">List Item</li>
<li class="3">List Item</li>
<li class="4">List Item</li>
<li class="5">List Item</li>
<li class="6">List Item</li>
</ul>
</div

Yeah I think a class name which contains only a number is incorrect.. So rather then a "0" or "1" it should be titled "number0" or "number1".

Thanks for your response!

Upvotes: 2

Views: 3600

Answers (3)

stef
stef

Reputation: 14268

You could use this jquery plugin: http://slightlymore.co.uk/ol/

From their docs:

<ol id="first_example">
  <li>Item number 1</li>
  <li>Item number 2</li>
  <li>Item number 3</li>
  <li>Item number 4</li>
</ol>


$("ol#first_example").niceOrderedLists();

However it doesn't add a class, but it probably will help you achieve what you are trying to do.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382696

You can do:

$('#imtheking li').each(function(index){
  $(this).attr('class', 'list_' + index);
});

Output will be:

<li class="list_0">List Item</li>
<li class="list_1">List Item</li>
<li class="list_2">List Item</li>
<li class="list_3">List Item</li>
<li class="list_4">List Item</li>
<li class="list_5">List Item</li>
<li class="list_6">List Item</li>

To retain the similar markup of yours and simply adding class is what you need, you can use addClass:

$('#imtheking li').each(function(index){
  $(this).addClass('list_' + index);
});

Upvotes: 4

Karl von Moor
Karl von Moor

Reputation: 8614

$("#imtheking li").each(function(index) {
  $(this).addClass('number' + index);
});

Upvotes: 6

Related Questions