When working with text nodes should I use the “data”, “nodeValue”, “textContent” or “wholeText” field? [duplicate]

笑着哭i 提交于 2019-11-28 20:38:36

问题


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

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

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?


回答1:


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

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



来源:https://stackoverflow.com/questions/12286975/when-working-with-text-nodes-should-i-use-the-data-nodevalue-textcontent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!