How do I choose between innerText or nodeValue?

a 夏天 提交于 2019-12-23 06:48:39

问题


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;

回答1:


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.




回答2:


  • 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



来源:https://stackoverflow.com/questions/1760126/how-do-i-choose-between-innertext-or-nodevalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!