24

For a given Text node in the DOM, one can use one of these properties to retrieve its text:

  • textContent
  • data
  • nodeValue
  • wholeText

But which one to use? Which one is the most reliable and cross-browser supported?

(If multiple properties are 100% reliable and cross-browser, then which one would be most appropriate?)

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385

2 Answers2

11

nodeValue should be is cross-browser compatible. It is part of the original DOM Level 2 specification.

Also have a look at the compatibility table of quirksmode.org for that matter (that's what I always use to see which properties are supported by which browsers).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 2
    If you look at that quirksmode sheet, you'll notice that `nodeValue` is "incomplete" in IE 5.5 whereas `data` is fully supported in that browser. It couldn't be less relevant, but still... `:)` – Šime Vidas Oct 07 '11 at 17:29
  • 2
    `data` is part of the DOM Level 2 spec as well, under the `CharacterData` interface. *No DOM objects correspond directly to CharacterData, though Text and others do inherit the interface from it.* (via: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-FF21A306) –  Oct 07 '11 at 17:56
  • @ŠimeVidas: Yes, but if you look at the note, then you will see that `nodeValue` just does not work with *attribute nodes* in IE 5.5, so it's fine for text nodes. I didn't know about `data`, to be honest ;) – Felix Kling Oct 07 '11 at 18:02
  • 4
    I've used `data` for years, and it's rock solid in all major browsers. – Tim Down Oct 08 '11 at 14:28
  • 1
    So many properties and methods are named `data` these days that having that in there tells you nothing about what the code is doing. Its meaning is not obvious. `innerText` and `textContent` (or even jquery.text()) make it immediately obvious what you're trying to do. – mastaBlasta Apr 30 '14 at 14:21
  • @mastaBlasta But be aware that `nodeValue` will also return content for `attribute` nodes, but the `data` will return undefined for non text nodes (and comments), and this is most probably what we want from simple text nodes. see this: https://stackoverflow.com/a/12287159/2803565 – S.Serpooshan May 03 '22 at 03:34
-1

When you're 100% sure that it's a text node you can use any of them.

Aron Woost
  • 19,268
  • 13
  • 43
  • 51