DOM - Child Nodes of a Node
Table of Contents
About
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
The best way to get the first child of a parent is through a chained querySelect selection
Example:
- A parent and a child
<div class="parent">
<p>Child</p>
</div>
- The selection of the p child and setting its color
let firstChild = document
.querySelector(".parent") // select the first node with the class parent
.querySelector("p"); // select the first p inside the parent node
firstChild.style.color="darkviolet";
- Output:
Why not using the firstChild property of a node ?
Because unfortunately, if there is a character (end of line included) between the two tag, the first child is a text node
Example:
<div class="parent">
<p>Child</p>
</div>
let firstChild = document.querySelector(".parent").firstChild;
if(firstChild.nodeType === Node.TEXT_NODE){
console.log("The first node is a text node containing an end of line character");
}
Add (Web API / Standard Javascript )
appendChild
- 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.
innerHtml
You can append also with the innerHTML property
node.innerHTML += "<div>Whatever</div>";
append
You can append node or text (not seen as HTML) with the append function.
Add Jquery
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);