JavaScriptArray
JavaScriptArray

Reputation: 140

Are text nodes automatically appended when other nodes are appended by JavaScript

I know that text nodes are automatically added for white space between nodes, at least when the nodes are added in the <body> tag in the html, but I am unsure about this when they are appended with JavaScript. I could not find any answers on the web about this case. I tested for it with the following code, but even though body.childNodes does not return text nodes between JS appended nodes, it appears like the formatting with the additional white space still is implemented. (My short html doc shows two paragraphs inserted directly by the <body> tag and two appended by JS.) I have placed what the browser console returned in comments under the call to console.log. Also, if the text nodes are still added when nodes are appended by JS, how would I remove them, since they don't appear in .childNodes?

<!doctype html>
<body>
  <p>1</p>
  <p>2</P>
</body>
<script>
  var i = document.createElement("p");
  i.textContent = "I";
  document.body.appendChild(i);
  var ii = document.createElement("p");
  ii.textContent = "II";
  document.body.appendChild(ii);
  console.log(document.body.childNodes);
  //NodeList {
  //0:	Text{}
  //1:	HTMLParagraphElement{}
  //2:	Text{}
  //3:	HTMLParagraphElement{}
  //4:	Text{}
  //5:	HTMLScriptElement{}
  //6:	HTMLParagraphElement{}
  //7:	HTMLParagraphElement{}
  //}
</script>

Upvotes: 0

Views: 185

Answers (1)

Oriol
Oriol

Reputation: 288520

Text nodes are not automagically inserted.

It's just that spaces in the HTML source are considered text. And text becomes a text node in the DOM.

If you remove all whitespace between elements in the HTML source, you won't have those text nodes.

And if you only add element nodes into the DOM, no text node will be inserted magically.

Note the inserted paragraphs are indeed in different lines. But that's not because a line break character appears between them. In fact, that would be useless, because all whitespace (including line breaks) collapse to a simple space (unless specified by white-space).

In fact, the paragraphs appear in different lines because they have display: block. Therefore,

In a block formatting context, boxes are laid out one after the other, vertically

Upvotes: 1

Related Questions