DOM - Child Nodes of a Node

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 (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: Firstchild

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 Insertadjacent

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);





Discover More
DOM - Element

An element is the most common type of node in the DOM. When you want to do something to an element, first you need to select it. A dom element is generally the memory representation of: an HTML element...
Domtree
DOM - Node

In DOM, every markup in an (XML|HTML) document is a node represented in a tree view. Every DOM node has at least: a , a name, and a value, which might or might not be empty. Node Type...



Share this page:
Follow us:
Task Runner