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;
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.
Basically, innerText: what's between the tags of the element. outerText: content of the element, including the tags.
Put simply, innerText is aware of the rendered appearance of text, while textContent is not.
Unlike innerHTML, textContent has better performance because its value is not parsed as HTML. For that reason, using textContent can also prevent Cross-Site Scripting (XSS) attacks. Unlike innerText, textContent isn't aware of CSS styling and will not trigger a reflow.
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 ofElemRef.innerText
isElemRef.childNodes[0].nodeValue
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With