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 (let 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>

firstChild

See the dedicated page: How to select the first child of a node element with DOM ? (Javascript examples)

Add (Web API / Standard Javascript )

appendChild

Browser - DOM Web Api

  • Duplicate of DOM - AppendChild
  • Note that appending a child that already exists on the tree will move it
  • 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 (HTML fragment or Node)

insertAdjacent with the afterbegin and beforeend parameter can append a string seen as HTML.

See What is InsertAdjacent and InsertAdjacentHTML and how to use them ?

innerHtml

You can append also with the innerHTML property

node.innerHTML += "<div>Bar</div>";

outerHtml

You can replaces the entire target element with the outerHTML property

node.outerHTML += "<div>Foo</div>";

append

You can append node or text (not seen as HTML) with the append function.

Add Jquery

See jQuery - Dom Manipulation

Remove

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

Property setting may also works (not recommended)

  • innerHtml to empty string
myNode.innerHTML = '';
  • if text
myNode.textContent = '';

Wrap

<div class="parent">
  <p>Child</p>
</div>
let parent = document.querySelector(".parent");
let firstChild = parent.querySelector("p");
let container = document.createElement("div");
container.style.backgroundColor = "skyblue";
container.style.margin = 2rem;
// move first child
container.appendChild(firstChild);
// move container
parent.appendChild(container);