Languages
[Edit]
EN

JavaScript - children vs childNodes

3 points
Created by:
Nathanial-Donald
584

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, while Node childNodes property returns all node children (elementstexts and comments).

 

Detailed description

Properties description:

PropertyDescription
children

Hint: elements are: <div>, <span>, <a>, <svg>, <head><body>, etc.

childNodes
  • each node and each element have that property,
  • is provided by Node interface,
  • contains all child nodes (it has NodeList type),

Hint: nodes are: elements, texts and comments.

Inheritance schema:

Node implementation by text, elements and comment.
Node implementation by text, elements and comment.

Node has:

  • childNodes

Text has:

  • childNodes
    (always empty)

Element has:

  • children
  • childNodes

Comment has:

  • childNodes
    (always empty)

 

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>

 

See also

  1. HTML - Element, Node, etc. inheritance

References

  1. Element.children - Web APIs | MDN
  2. Node.childNodes - Web APIs | MDN

Alternative titles

  1. JavaScript - element children and childNodes differences
  2. JavaScript - difference between element children and child nodes
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join