1

I have a simple list in HTML and I'd like to add the numbers in javascript.

The li elements are hard coded (content changes every time) but the number of elements might change. That's why I'd like to dynamically add the numbers in the number class without dynamically rewrite the code in JS (I can't just do text(<li>${num} ${variable}</li>)

This is the HTML

<ul>
  <li><span class="number">1</span> Something</li>
  <li><span class="number">2</span> Something else</li>
</ul>

JS const list = $('ul').length; let num;

  for (let num = 0; num < list; num++) {
    $('.number').append(num); // The output is 0123 for all the numbers...
  }

Example:

I have 3 li elements "1. Potatoes", "2. Carrots", "3. Cucumber";

Elements change, now I have 2 li elements "1. Potatoes", "2. Cucumber";

9
  • 2
    SO you do not want to use an ol? Commented Jan 30, 2019 at 3:00
  • Nope. I mean I definitely could but since I am practising JS I was wondering if there was a way using JS only Commented Jan 30, 2019 at 3:02
  • So how are you building the lis? Commented Jan 30, 2019 at 3:03
  • The list itself is hardcoded html, the list is repeated in every page (always the same, I use PHP include) but one element is deleted in every page, so I need the numbers to be dynamically updated Commented Jan 30, 2019 at 3:06
  • Seems weird you do not write it with whatever spits it out.... Commented Jan 30, 2019 at 3:07

3 Answers 3

2

One approach is using jQuery .each()

$(".number").each(function(index){
  let num = index + 1;
  $(this).text(num);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly and it was very simple.
1

The reason why your solution does not work is you are selecting all the number elements on each iteration. $(".number").append(...) So on every loop you select al the elements and you append to them. That is why the numbers are added to each one.

You should be selecting the index you are on....

var numbers = $('.number')  // select all the numbers
for (let num = 0; num < list; num++) {  // loop
  numbers.eq(i).text(num);  // set the text of the current index
}

It would be better just use text() with a function if you want to go the jQuery way

$('.number').text(function(index) {
  return (index + 1);
});

Now your other options:

Best option, have whatever spits out the HTML generate it....

Next option, You could just use an ordered list and you would get the numbers.

Another option, you do not need JavaScript, pure CSS can insert the number

ol {
  margin :0;
  padding:0;
  counter-reset:li;
  list-style: none;
}

ol li:before {
  content:counter(li); 
  counter-increment:li;
  font-weight: bold;
  padding-right: .5em;
}
<ol>
  <li>Apple</li>
  <li>Pear</li>
  <li>Bacon</li>
</ol>

or if you really want JavaScript

document.querySelectorAll("#myList li").forEach(function(li, i) {
  li.innerHTML = '<span>' + (i + 1) + '</span>' + li.innerHTML
})
ol {
  margin: 0;
  padding: 0;
  counter-reset: li;
  list-style: none;
}

ol li span {
  font-weight: bold;
  padding-right: .5em;
}
<ol id="myList">
  <li>Apple</li>
  <li>Pear</li>
  <li>Bacon</li>
</ol>

if the spans exist, than just change the text

document.querySelectorAll("#myList li span").forEach(function(span, i) {
  span.innerHTML = (i + 1)
})
ol {
  margin: 0;
  padding: 0;
  counter-reset: li;
  list-style: none;
}

ol li span {
  font-weight: bold;
  padding-right: .5em;
}
<ol id="myList">
  <li><span></span>Apple</li>
  <li><span></span>Pear</li>
  <li><span></span>Bacon</li>
</ol>

Comments

0

One approach for what you want is to create an update method that will reassign all numbers to the <li> elements, and call this method every time the <ul> is changed. Take a look at the next example:

$(document).ready(function()
{
    updateNumbers();
    
    setTimeout(() =>
    {
        $(".to-remove").parent().remove();
        updateNumbers();
    }, 2000);
});

function updateNumbers()
{
    $('ul li').each(function(idx, elem)
    {
        $(this).find(".number").text(idx + 1);
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><span class="number"></span> Something</li>
  <li><span class="number to-remove"></span> Something else</li>
  <li><span class="number"></span> Something else again</li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.