Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 590
hippietrail Avatar asked Sep 05 '12 17:09

hippietrail


People also ask

What is the difference between innerText and textContent?

textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements.

What will be the nodeValue for attribute nodes?

A string containing the value of the current node, if any. For the document itself, nodeValue returns null . For text, comment, and CDATA nodes, nodeValue returns the content of the node. For attribute nodes, the value of the attribute is returned.

What is nodeValue?

Definition and Usage The nodeValue property sets or returns the value of a node. If the node is an element node, the nodeValue property will return null. Note: If you want to return the text of an element, remember that text is always inside a Text node, and you will have to return the Text node's node value (element.


1 Answers

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

like image 196
raina77ow Avatar answered Sep 28 '22 04:09

raina77ow