How do I choose between innerText or nodeValue?
Asked Answered
P

2

24

When I need to change a text within a span element, which one should I use and what is the difference:

var spnDetailDisplay=document.getElementById('spnDetailDisplay');
spnDetailDisplay.innerText=sDetail;

or

 var spnDetailDisplay=document.getElementById('spnDetailDisplay');
 spnDetailDisplay.childNodes[0].nodeValue=sDetail;
Permatron answered 19/11, 2009 at 0:28 Comment(1)
Does this answer your question? innerText vs innerHTML vs label vs text vs textContent vs outerTextElide
P
18

For elements with text content, they're the same. See this MDC article for information on nodeValue.

From this article:

If the element has no sub-elements, just text, then it (normally) has one child node, accessed as ElemRef.childNodes[0]. In such precise case, the W3C web standards equivalent of ElemRef.innerText is ElemRef.childNodes[0].nodeValue.

Phylissphyll answered 19/11, 2009 at 0:32 Comment(0)
A
4
  • nodeValue is standard recommendation W3C.
  • innerText is Internet Explorer specific, not the standard. And:
    • Does not return content of <script> and <style>.
    • Style awareness, does not return text of hidden elements.
    • CSS styling awareness, it will trigger a reflow.

However in versions of all major browsers as of March of 2016 innerText is supported.

In general, they are similar, but if you need the best performance, nodeValue should be used.

Link for performance test: https://jsperf.com/read-innerhtml-vs-innertext-vs-nodevalue-vs-textcontent/13

Abohm answered 2/9, 2015 at 1:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.