DOM - Child Nodes of a Node

> (World Wide) Web - (W3|WWW) > The Document Object Model W3C API Interface (DOM)

1 - About

Child Nodes of an element in the dom tree

Advertising

3 - Management

3.1 - Get

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>

3.2 - Add

3.2.1 - Web API Add

Browser - DOM Web Api

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

3.2.2 - Jquery After

  • The HTML
  <p class="beauty-blue">The first beauty-blue paragraph</p>
  <p>The second paragraph</p>
  • The CSS for the class
.beauty-blue { color: blueviolet; }
  • The Javascript script with jQuery After function.
  • We select all P and we add a paragraph after.
$('p').after('<div>After</div>');
  • With a callback
$('p').after( function() {
  if (this.className != ""){
      return "<div>The class name of the previous element is " + this.className + "</div>";
  } else {
     return "<div>The previous element has no class name</div>";
  }
});
  • The result:

Advertising
web/dom/child.txt · Last modified: 2019/02/09 11:41 by gerardnico