使用文本节点时,我应该使用“data”,“nodeValue”,“textContent”还是“wholeText”字段? [重复]

时间:2021-12-01 17:42:45

Possible Duplicate:
How to retrieve the text of a DOM Text node?

可能重复:如何检索DOM Text节点的文本?

In my experiments to handle DOM mutation observers I've noticed that when the target is a text node there are four fields all containing the new text of the node.

在我处理DOM变异观察者的实验中,我注意到当目标是文本节点时,有四个字段都包含节点的新文本。

  • data
  • 数据
  • nodeValue
  • 的nodeValue
  • textContent
  • 的textContent
  • wholeText
  • wholeText

Is there a "best practice" for which of these fields I should use?

对于我应该使用哪些领域,是否有“最佳实践”?

Are some just for compatibility with other browsers or older DOM standards? Does it make a difference whether I'm reading vs modifying the text? If one is best what is the purpose of the others?

有些只是为了兼容其他浏览器或旧的DOM标准吗?是否我正在阅读和修改文本会有所不同吗?如果最好的是其他人的目的是什么?

1 个解决方案

#1


28  

Of all these I'd choose data: it is defined for the nodes implementing CharacterData interface (Text and Comment ones) only. Trying to access this property for the others gives undefined.

在所有这些中,我选择数据:它仅为实现CharacterData接口(文本和注释)的节点定义。尝试为其他人访问此属性会给出undefined。

nodeValue is essentially the same as data for text nodes, but is actually defined for attribute and comment nodes as well. And I usually want my programs to fail early. )

nodeValue与文本节点的数据基本相同,但实际上也是为属性和注释节点定义的。我通常希望我的程序尽早失败。 )

textContent is, for me, something completely different, as it represents the text content of a node and its descendants. This, along with wholeText, perhaps should be used more to collect texts from more complex structures than a single text node.

对我来说,textContent是完全不同的东西,因为它代表节点及其后代的文本内容。这与整个文本一起,可能应该更多地用于从比单个文本节点更复杂的结构中收集文本。

Said all that, textContent and wholeText were defined in DOM Level 3 (= more modern).

说了这么多,textContent和wholeText都是在DOM Level 3中定义的(=更现代)。

#1


28  

Of all these I'd choose data: it is defined for the nodes implementing CharacterData interface (Text and Comment ones) only. Trying to access this property for the others gives undefined.

在所有这些中,我选择数据:它仅为实现CharacterData接口(文本和注释)的节点定义。尝试为其他人访问此属性会给出undefined。

nodeValue is essentially the same as data for text nodes, but is actually defined for attribute and comment nodes as well. And I usually want my programs to fail early. )

nodeValue与文本节点的数据基本相同,但实际上也是为属性和注释节点定义的。我通常希望我的程序尽早失败。 )

textContent is, for me, something completely different, as it represents the text content of a node and its descendants. This, along with wholeText, perhaps should be used more to collect texts from more complex structures than a single text node.

对我来说,textContent是完全不同的东西,因为它代表节点及其后代的文本内容。这与整个文本一起,可能应该更多地用于从比单个文本节点更复杂的结构中收集文本。

Said all that, textContent and wholeText were defined in DOM Level 3 (= more modern).

说了这么多,textContent和wholeText都是在DOM Level 3中定义的(=更现代)。