Search code examples
javascriptlistreplacenodesinnerhtml

Concatenate a list of numbers into a list with .innerHTML


I've got a list of items and I need to create a function that puts a number front of each item in the list. So "pine nuts", would become "2. pine nuts"

Here's the list I'm passing in (with the parameter ulPassed) -

    <li id="one" class="hot"><em>fresh</em> figs</li>
    <li id="two" class="hot">pine nuts</li>
    <li id="three" class="hot">honey</li>
    <li id="four" class="cold">balsamic vinegar</li>
    <li id="five" class="cold">yoghurt coated banana chips</li>

Here's my code so far -

function swapInnerHTML(ulPassed){

ulPassed = ulPassed.innerHTML;

var grocList = document.getElementById('groceries');
var listItems = grocList.getElementsByTagName('li');

var listNumber = 1;

var count = 0;
for (count = 0; count < ulPassed.length; count++) {
    var thisItem = listItems[count].getAttribute('class');      //pointing towards each class item
    var foodText = thisItem.firstChild.nodeValue;   //pointing towards the child node of each item
    foodText = foodText.replace(foodText, listNumber+". "+foodText); //replace the text
    thisItem.firstChild.nodeValue = foodText; //update the text
    listNumber++; //next list number
}

console.log(ulPassed);
return ulPassed;

}

So I'm attempting a for loop to cycle through the list, and replace each of the food items with itself but with a list number in front of them, also a ". ". In that same loop I'm increasing the list number. The problem I'm having is getting it to replace the text itself, I feel as if I'm pretty close, but I don't feel as if I'm using the firstChild.nodeValue correctly.

Any help would be great. Thanks!


Solution

  • Without using Javascript you could use an ordered list <ol> instead of a unordered list <ul> especially if this is done only for a visual purpose. Also, counters in CSS can be easily styled, e.g.

    ul {
      counter-reset: food 0;
    }
    
    li::before {
      counter-increment: food;
      content: counter(food) ". "; 
    }
    <ul>
       <li class="hot"><em>fresh</em> figs</li>
       <li class="hot">pine nuts</li>
       <li class="hot">honey</li>
       <li class="cold">balsamic vinegar</li>
       <li class="cold">yoghurt coated banana chips</li>
    </ul>


    Otherwise in Javascript you could loop over all the list-items and set their innerHTML property using the index inside the map function

    [...document.querySelectorAll('li')].map((food, i) => 
        food.innerHTML = [++i, food.innerHTML].join('. ')  
    );
    <ul>
       <li class="hot"><em>fresh</em> figs</li>
       <li class="hot">pine nuts</li>
       <li class="hot">honey</li>
       <li class="cold">balsamic vinegar</li>
       <li class="cold">yoghurt coated banana chips</li>
    </ul>