What is the difference between children and childNodes in JavaScript?
- childNodes:
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
- children
The children is a property of element which 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.
<!DOCTYPE html> < html > < body > < style > p { color: green; } </ style > < center > < h1 style = "color:green" >GeeksforGeeks</ 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 > </ center > </ body > </ html > |
Output:
Before:
After:
Example 2: This example illustrates the property of children.
<!DOCTYPE html> < html > < body > < style > p { color: green; } </ style > < center > < h1 style = "color:green" >GeeksforGeeks</ 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 > </ center > </ body > </ html > |
Output:
Before:
After:
Supported Browsers:
- Google Chrome
- Mozilla Firefox
- Apple Safari
- Opera
- Internet Explorer/Edge