EN
JavaScript - children vs childNodes
3
points
In this article, we would like to show you the difference between element's children
and childNodes
properties in JavaScript.
Simple comparision:
Element
children
property returns only element children, whileNode
childNodes
property returns all node children (elements, texts and comments).
Detailed description
Properties description:
Property | Description |
children |
|
childNodes |
|
Inheritance schema:
![]() |
Node has:
Text has:
Element has:
Comment has:
|
Practical example
In this section, we present a practical an example with both children
and childNodes
properties so you can clearly see the difference between them.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="element"><span>Text inside</span>Text outside<!-- comment --></div>
<script>
var element = document.querySelector('#element');
var children = element.children;
var childNodes = element.childNodes; // element is both node and element, so we have childNodes
console.log(children.length); // 1 // 1 child element: span element `<span>Text inside</span>`
console.log(childNodes.length); // 3 // 3 child nodes: span element `<span>Text inside</span>`
// text node `Text outside`
// comment node `<!-- comment -->`
</script>
</body>
</html>