Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make appendchild method on top of elements

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading