当使用文本节点时,我应该使用“数据”,“nodeValue”,“textContent”或“全文”领域? [英] When working with text nodes should I use the "data", "nodeValue", "textContent" or "wholeText" field?
问题描述
可能重复:
如何检索DOM Text节点的文本?
在我处理DOM突变观察者的实验中,我注意到当目标
是一个文本节点时,有四个字段都包含节点的新文本。
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.
-
数据
-
nodeValue
-
textContent
-
wholeText
data
nodeValue
textContent
wholeText
有没有一个最佳实践我应该使用这些字段?
Is there a "best practice" for which of these fields I should use?
有些只是为了与其他浏览器或旧的DOM标准兼容吗?无论我正在阅读还是修改文字,都有所不同吗?如果一个人最好是他人的目的是什么?
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?
推荐答案
所有这些我会选择数据
:它是为执行的节点定义的 CharacterData 界面( 文本 和 评论 )。试图访问这个属性为其他人赋予 undefined
。
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
.
nodeValue 基本上与数据
相同,但实际上是为属性和注释节点。我通常希望我的程序能够早日失败。 )
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. )
textContent 是对我来说,完全不同的东西,因为它代表节点及其后代的文本内容。这与整个文本一起使用,也许应该更多地用于从更复杂的结构中收集文本比起单个文本节点。
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
和 wholeText
在DOM Level 3(=更现代)中定义。
Said all that, textContent
and wholeText
were defined in DOM Level 3 (= more modern).
这篇关于当使用文本节点时,我应该使用“数据”,“nodeValue”,“textContent”或“全文”领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!