DOM - Child Nodes of a Node

About

Child Nodes of an element in the dom tree

Management

Get

via Selector

Via child selector, you can select element that are child of another element.

via childNodes

The childNodes property of an element returns a collection of child Node.

var divChildNodes  = document.querySelector("div").childNodes;

console.log("We have " + divChildNodes.length + " nodes");

for (var i = 0; i < divChildNodes.length; i++) {
        console.log("Node ("+i+") is a "+divChildNodes[i]+" and has the following content: "+divChildNodes[i].textContent);
}
<div>
<p>First paragraph</p>
<p>Second paragraph</p>
<b>
</div>

Add

Web API Add

appendChild

Browser - DOM Web Api

Duplicate of DOM - AppendChild

  • with the createElement
for(var i = 1; i <= 4; i++) {
        var myDiv = document.createElement('div');
        myDiv.className = "buttonClass";
        myDiv.innerHTML = "Div content "+i;
        document.body.appendChild(myDiv);
}
insertAdjacent

insertAdjacent with the afterbegin and beforeend parameter

Jquery

Remove

  • Remove all child
let parent = document.querySelector("parent");
while (parent.firstChild) {
       parent.firstChild.remove()
}

Powered by ComboStrap