Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptWhat is the difference between children and childNodes in JavaScript?

What is the difference between children and childNodes in JavaScript?

DOM childNodes Property: The childNodes property is a property of Node in Javascript and is used to return a Nodelist of child nodes. Nodelist items are objects, not strings and they can be accessed using index numbers. The first childNode starts at index 0

Syntax

element.childNodes

DOM children Property: The children are a property of an element that returns the child elements of an element as objects. 

Syntax

element.children

The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes. 

Example 1: This example illustrates the property of childNodes. 

html




<h1 style="color:green">neveropen</h1>
<h2>childNodes</h2>
<button onclick="childNode()">
    Try it
</button>
  
<p id="geek"></p>
  
<script>
    function childNode() {
        //accessing all the child nodes present in our code
        var childNode =
            document.body.childNodes;
        var string = "";
        var i;
      
        for (i = 0; i < childNode.length; i++) {
            string = string + childNode[i].nodeName + "<br>";
        }
      
        //appending the child nodes to paragraph with id "geek"
        document.getElementById(
        "geek").innerHTML = string;
    }
</script>


Output:

What is the difference between children and childNodes in JavaScript?

What is the difference between children and childNodes in JavaScript?

Example 2: This example illustrates the property of children. 

html




<h1 style="color:green">neveropen</h1>
<h2>children</h2>
  
<button onclick="myChildren()">
    Try it
</button>
  
<p id="geek"></p>
  
<script>
    function myChildren() {
        var c = document.body.children;
        var string = "";
        var i;
        for (i = 0; i < c.length; i++) {
            string = string + c[i].tagName + "<br>";
        }
      
        document.getElementById(
        "geek").innerHTML = string;
    }
</script>


Output:

What is the difference between children and childNodes in JavaScript?

What is the difference between children and childNodes in JavaScript?

RELATED ARTICLES

Most Popular

Recent Comments