如何在innerText 或nodeValue 之间进行选择?

发布于 2024-08-11 22:23:48 字数 325 浏览 3 评论 0原文

当我需要更改 span 元素中的文本时,我应该使用哪一个以及有什么区别:

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

 var spnDetailDisplay=document.getElementById('spnDetailDisplay');
 spnDetailDisplay.childNodes[0].nodeValue=sDetail;

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

可是我不能没有你 2024-08-18 22:23:48

对于具有文本内容的元素,它们是相同的。有关 nodeValue 的信息,请参阅这篇 MDC 文章

来自这篇文章

如果该元素没有子元素,只有文本,那么它(通常)有一个子节点,可通过 ElemRef.childNodes[0] 访问。在这种精确的情况下,与 ElemRef.innerText 等效的 W3C Web 标准是 ElemRef.childNodes[0].nodeValue

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.

吻安 2024-08-18 22:23:48
  • nodeValue是W3C标准推荐。
  • innerText 是特定于 Internet Explorer 的,而不是标准。和:
    • 不返回

然而,截至 2016 年 3 月,所有主要浏览器的版本都支持innerText。

一般来说,它们是相似的,但如果您需要最佳性能,则应使用nodeValue

性能测试链接:https://jsperf.com /read-innerhtml-vs-innertext-vs-nodevalue-vs-textcontent/13

  • 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文