什么被认为是文本节点?
What is considered a text node?
一般HTML中的标签之间如果有文本就成为文本节点。然而,这并非总是如此。考虑这个例子:
<p>
<a href="hello.html">hello</a> <a href="world.html">world</a>
</p>
这里,<p>
和第一个<a ...>
之间的换行符和2个space不会在DOM中作为文本节点出现,至少不在 Chrome。 hello
和 world
当然是文本节点。似乎只有 whitespace 的序列不会显示为文本节点,但情况并非总是如此:在这个例子中,2 个链接之间的 space 是一个文本节点。
Chrome如何决定什么成为文本节点?
在 Chrome 中试试这个,你会看到 p
的 firstChild
是 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>
编辑:
看来你甚至不能在 Chrome 中尝试,因为它抛出 "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag."
SO 需要更新他们的代码片段实现,因为它显然现在已经损坏了。
编辑 2:
您可以在 Chrome 中查看:https://codepen.io/anon/pen/qQPdbz?editors=1111
一般HTML中的标签之间如果有文本就成为文本节点。然而,这并非总是如此。考虑这个例子:
<p>
<a href="hello.html">hello</a> <a href="world.html">world</a>
</p>
这里,<p>
和第一个<a ...>
之间的换行符和2个space不会在DOM中作为文本节点出现,至少不在 Chrome。 hello
和 world
当然是文本节点。似乎只有 whitespace 的序列不会显示为文本节点,但情况并非总是如此:在这个例子中,2 个链接之间的 space 是一个文本节点。
Chrome如何决定什么成为文本节点?
在 Chrome 中试试这个,你会看到 p
的 firstChild
是 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>
编辑:
看来你甚至不能在 Chrome 中尝试,因为它抛出 "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag."
SO 需要更新他们的代码片段实现,因为它显然现在已经损坏了。
编辑 2:
您可以在 Chrome 中查看:https://codepen.io/anon/pen/qQPdbz?editors=1111