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?

1
  • 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 4 at 2:37

1 Answer 1

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

3
  • 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! (-: Sep 5, 2012 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, 2014 at 20:56
  • 7
    Correction: data is not defined "for text nodes only", but for the CharacterData interface, which is not only inherit by Text nodes, but also Comment nodes.
    – Rob W
    Aug 4, 2014 at 10:36

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.