To append a DOM element to a specific position, you can use insertBefore
:
parent.insertBefore(newElement, parent.children[i])
Where i
is the position of the next element. In your case, the parent is one ol
element and children are its li
elements. You want to insert an element at the second position so i
is 2
.
To apply this to every ol
, just make a loop on every parent element you have with your selection by class.
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>
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>
really thanks for the help, actually im not using jquery so i dont know hehe, what i want is the list get something like this 1.Element N1 2.Element N3 3.Element N2 im using js to make it to both ol from HTML
So… this example don’t use jQuery.