What are unexpected text nodes?

Viewed 1191

I have a parent Element containing just one child element so as far as I know this parent element has one child node but in console there are three nodes two of them is text node. This is clear in this image.unexpected tex node in javascript Now my questions are:

1.Where does this text nodes come from?

  1. Are these text node built in? What is the necessity of them?

  2. What are the rules of them?

var container = document.getElementById('container');
var children = container.childNodes;
console.log(children);
<div id="container">
  <div id='test'></div>
</div>

1 Answers

Two of the childNodes are newlines. From MDN:

childNodes includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead.

See the output of the below snippet, if you do not understand what I mean:

var container = document.getElementById('container');
var chlds = container.childNodes;
chlds.forEach(c => console.log(c.nodeName + ":" + c.innerText));
<div id="container">
  <div id='test'></div>
</div>

To answer your follow-up questions, the text nodes are there as they exist in the document, due to the document having newlines (or other non-element markup). children is a far more reliable way to get the child nodes of an element, as childNodes output can vary between unminified and minified HTML code, which could cause you some headaches.

Related