Difficulty understanding childNodes/chidNodes length property

I understand that whitespace, comments are all nodes in JavaScript… But I really don’t understand why the length of childNodes is 7… A simple explanation will be appreciated , thanks

<div id="myDIV">
  <p> This is paragraph 1</p>
  <p>This is paragraph 2</p>
  <p>This is paragraph 3</p>
</div>
var c = document.getElementById("myDIV").childNodes.length;
console.log(c); //7

Hi @adefesoq, if you log those child nodes (not just the length) you’ll get something like this:

var nodes = document.getElementById("myDIV").childNodes;
console.log(nodes);
// NodeList(7) [ #text, p, #text, p, #text, p, #text ]

You can then expand the list as well as individual nodes in the console for further inspection – you have 3 p element nodes, and 4 text nodes containing line breaks around them.

Understood, thanks.

As an aside, the property you might be wanting to use (depending on browser support) is .children ( that gives you a count of actual HTML elements that are direct children of a parent element.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.