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>
Use insertBefore if you want to add a node anywhere before the end of its container.
parentElement.insertBefore(newNode, currentThirdNode);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With