Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to appendChild as third child

I want to add a new child node, after a specified node, as the third child node.

<ul id="menu">
    <li>one</li>
    <li>tow</li>
    <li>three</li>
    <li>four</li>
</ul>

<script>
var li = document.createElement("li");
document.getElementById("menu").appendChild(li);
var sometext = document.createTextNode("third one");
li.appendChild(sometext); 
</script>
like image 596
JS-Hero Avatar asked Dec 10 '25 13:12

JS-Hero


2 Answers

Use insertBefore if you want to add a node anywhere before the end of its container.

parentElement.insertBefore(newNode, currentThirdNode);
like image 69
Quentin Avatar answered Dec 12 '25 03:12

Quentin


keep in mind that there is a difference in childNodes, namely siblings and ElementSiblings. a textNode is a Node, but not an Element. so if you want to insert an element into the the DOM, use nextElementSibling | previousElementSibling and appendChild | insertBefore and the parent's children attribute that only contains Elements like this:

function insertAsThird( element, parent ){
  if ( parent.children.length > 2 ){
   parent.insertBefore(element, parent.children[2]);
 }
 else parent.appendChild(element);
}

and use it like this:

insertAsThird( yourThirdElement, document.getElementById("your target parent"));

if you want to to work on childNodes, not Elements, just change the parent.children parts to parent.childNodes

like image 39
tenshou Avatar answered Dec 12 '25 01:12

tenshou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!