What is considered a text node?

325 Views Asked by At

Generally if there is text between tags in HTML, it becomes a text node. However, this is not always the case. Consider this example:

<p>
  <a href="hello.html">hello</a> <a href="world.html">world</a>
</p>

Here, the linebreak and 2 spaces between the <p> and the first <a ...> won't appear as a text node in the DOM, at least not in Chrome. hello and world will of course be text nodes. It would seem that sequences of only whitespace don't appear as text nodes, but that's not always the case: In this example, the space between the 2 links is a text node.

How does Chrome decide what becomes a text node?

1

There are 1 best solutions below

1
On BEST ANSWER

Try this in Chrome and you'll see the firstChild of p is Text:

let p = document.querySelector('p')

console.log(p.firstChild.constructor.name)
<p>
  <a href="hello.html">hello</a> <a href="world.html">world</a>
</p>

Edit:

It seems you cannot even try that in Chrome as it throws "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag."

SO needs to update their snippet implementation as it obviously is broken as of now.

Edit 2:

You can check it in Chrome here: https://codepen.io/anon/pen/qQPdbz?editors=1111