Home > Software engineering >  How to make appendchild method on top of elements
How to make appendchild method on top of elements

Time:08-31

I am doing a ul elements and it spawns li elements using js

var newli = document.createElement("li")
newli.innerHTML = "1"
document.getElementById('ulmain').appendChild(newli);
<ul id="ulmain">
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

and as you can see, the 1 spawned below the 4. But I need the 1 spawn below of 2

CodePudding user response:

You can't use the appendChild() method adds a node to the end of the list of children of a specified parent.

You can use prepend() to insert before the first child of the ul

document.getElementById('ulmain').prepend(newli);

Working Code

var newli = document.createElement("li")
newli.innerHTML = "1"
document.getElementById('ulmain').prepend(newli);
<ul id="ulmain">
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

  • Related