DOM - Child Nodes of a Node


Child Nodes of an element in the dom tree



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);
<p>First paragraph</p>
<p>Second paragraph</p>


The best way to get the first child of a parent is through a chained querySelect selection


  • A parent and a child
<div class="parent">
  • 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"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


<div class="parent">
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 )


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;

insertAdjacent (HTML fragment or Node)

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


You can append also with the innerHTML property

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


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

Add Jquery


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

Property setting may also works (not recommended)

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


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

Powered by ComboStrap