当使用文本节点时,我应该使用“data”,“nodeValue”,“textContent”或“整个文本”领域? [英] When working with text nodes should I use the "data", "nodeValue", "textContent" or "wholeText" field?

查看:195
本文介绍了当使用文本节点时,我应该使用“data”,“nodeValue”,“textContent”或“整个文本”领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何检索DOM文本节点的文本?

在我处理DOM变化观察者的实验中,我注意到当 target 是一个文本节点时,节点的新文本。

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.


  • data

  • nodeValue

  • textContent

  • wholeText

  • data
  • nodeValue
  • textContent
  • wholeText

这些字段我应该使用?

有些只是为了与其他浏览器或旧的DOM标准兼容吗?它是否会影响我是否正在阅读VS修改文本?

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 对于文本节点基本上与 data 相同,但实际上是为属性和注释节点。我通常希望我的程序提前失败。 )

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).

这篇关于当使用文本节点时,我应该使用“data”,“nodeValue”,“textContent”或“整个文本”领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆