58

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?

Community
  • 1
  • 1
hippietrail
  • 15,848
  • 18
  • 99
  • 158
  • 3
    This question is closed incorrectly. The answer to this question is much better than for the "duplicate", has much more upvotes and **explains the exact difference between the properties**. – Athari Jan 04 '23 at 02:37

1 Answers1

54

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

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • I actually used `data` too before I asked here. I think partly because it was first alphabetically and partly because it was the most concise. Good to have more deterministic reasons though! (-: – hippietrail Sep 05 '12 at 18:03
  • Actually it appears that of these four, only textContent is writeable... (or rather, it's the only one that seems to update that actual displayed content). why is this? – Michael Jan 25 '14 at 20:56
  • 7
    Correction: `data` is not defined "for text nodes only", but for the [CharacterData interface](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-FF21A306), which is not only inherit by [Text nodes](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1312295772), but also [Comment nodes](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1728279322). – Rob W Aug 04 '14 at 10:36