Search code examples
javascripthtml-listsappendchild

Creating Multiple li on multiple ol and put them in specific position


I'm sorry about my bad English, I'm learning js hope you can help me =)

What I want is to create a li element on both ol with JS and put them in the second position in the list, when I do for the 1 ol it works, but when I attempt to put it into a loop (for), it's not working =( I'm pretty noob at this, if you can help me I will appreciate it a lot thanks

for (i = 0; i > 1; i++) {
  var newelementlist = document.createElement("li");
  var newcontent = document.createTextNode("Element N3");
  newelementlist.appendChild(newcontent);

  var container = document.getElementsByClassName("list")[i];
  var lastson = container.lastElementChild;
  container.appendChild(newelementlist);
  container.insertBefore(newelementlist, lastson);
}
<body>
  <ol class="list">
    <li>Element N1</li>
    <li>Element N2</li>
  </ol>
  <br>
  <ol class="list">
    <li>Element N1</li>
    <li>Element N2</li>
  </ol>
  <br>
</body>


Solution

  • If I understand you well, maybe is it of that you need:

    let ols = [...document.querySelectorAll('ol.list')]; // get all <ol class="list">
    ols.forEach(ol => { // iterate...
        let lis = [...ol.querySelectorAll('li')]; // get all <li> child
      lis.forEach(li => ol.removeChild(li)); // iterate to remove from <ol> parent
      let newLi = document.createElement("li"); // create your new <li>
      let newContent = document.createTextNode('New Element'); // create new content for new <li>
      newLi.appendChild(newContent); // append the content into new <li>
        lis.splice(1, 0, newLi); // add the new <li> at the second position in array (index 1)
      lis.forEach(li => ol.appendChild(li)); // append all <li> on current <ol>
    })
    <html>
    <head>
    </head>
    <body>
          <ol class="list">
            <li>Element N1</li>
            <li>Element N2</li>
          </ol>
          <br>
          <ol class="list">
            <li>Element N1</li>
            <li>Element N2</li>
          </ol>
          <br>
    </body>
    </html>