An element’s children property in Document Object Model (DOM) returns a collection of its child elements as an html collection object. The elements in the collection are sorted as they appear in the source code and can be accessed by index numbers. The length property of the HTMLCollection object can be used to determine the number of child elements, as well as to loop through the child elements.
The childNodes property, part of Core Level 1 Element Object, returns a collection of a node's child nodes, as a NodeList object. The difference between children property and childNodes, is that childNodes contain all nodes, including text nodes and comment nodes, while children only contains element nodes.
Example of JavaScript's childNodes property
<html>
<body>
<style>
p {font-style:italic; font-weight:bold; color:#444;}
h6 {padding:2px; margin:0px 10px; font-family:"Calibri"; color:#55f;}
</style>
<script>
var element = document.createElement("p");
element.className = "para";
var text = document.createTextNode("Hello World!");
element.appendChild(text);
var text2 = document.createTextNode("Good morning!");
element.appendChild(text2);
document.body.appendChild(element);
document.body.innerHTML += "<h6>1. Child Node length: " + element.childNodes.length + "</h6>";
document.body.innerHTML += "<h6>2. Elements by tag name: " + document.getElementsByTagName("P").length + "</h6>";
</script>
</body>
</html>
Comments
No comments have been made yet.
Please login to leave a comment. Login now