Pepe
Pepe

Reputation: 1002

Count div by div and show number per div, not total numbers

I only found lots of answers to show the total number of some special divs, like this way:

$('.someclass').length

... but my problem is, that I want to count div by div with a numerical sequence.

For example, I have the following list ...

<ul>
  <li>Some content</li>
  <li>Some content</li>
  <li>Some content</li>
</ul>

... now I want to count every li element and add automatically a number from low to high, like this:

<ul>
  <li>Some content <span class="number">1</span></li>
  <li>Some content <span class="number">2</span></li>
  <li>Some content <span class="number">3</span></li>
</ul>

How is this possible?

Upvotes: 0

Views: 155

Answers (3)

A. Wolff
A. Wolff

Reputation: 74410

You could use the index:

$('ul li').append(function() {
  return ' <span>' + ($(this).index() + 1) + '</span>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>Some content</li>
  <li>Some content</li>
  <li>Some content</li>
</ul>
<ul>
  <li>Some content</li>
  <li>Some content</li>
  <li>Some content</li>
</ul>

Upvotes: 1

NiallMitch14
NiallMitch14

Reputation: 1229

Try having your HTML like this:

<ul class="someClass">
  <li>Some content</li>
  <li>Some content</li>
  <li>Some content</li>
</ul>

Then to do what you're trying to do in JQuery:

var count = 0;
$('.someClass li').each(function(){
    count++;
    $(this).append('<span class="number">'+count+'</span>');
});

Upvotes: 0

jcubic
jcubic

Reputation: 66650

Try this:

$(function() {
  $('ul li').each(function(i) {
    var self = $(this);
    self.html(self.html() + ' <span class="number">' + (i+1) + '</span>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>Some content</li>
  <li>Some content</li>
  <li>Some content</li>
</ul>

Upvotes: 1

Related Questions