简体   繁体   English

nodeValue 与 innerHTML 和 textContent。 如何选择?

[英]nodeValue vs innerHTML and textContent. How to choose?

I'm using plain js to alter the inner text of a label element, and I wasn't sure on what grounds I should use innerHTML or nodeValue or textContent.我正在使用纯 js 来更改标签元素的内部文本,但我不确定应该使用 innerHTML 或 nodeValue 或 textContent 的理由。 I don't need to create a new node or change the HTML elements or anything — just replace the text.我不需要创建新节点或更改 HTML 元素或其他任何东西 — 只需替换文本即可。 Here's an example of the code:下面是代码示例:

var myLabel = document.getElementById("#someLabel");
myLabel.innerHTML = "Some new label text!"; // this works

myLabel.firstChild.nodeValue = "Some new label text!"; // this also works.

myLabel.textContent = "Some new label text!"; // this also works.

I looked through the jQuery source, and it uses nodeValue exactly one time but innerHTML and textContent several times.我查看了 jQuery 源代码,它只使用了一次 nodeValue,但多次使用了 innerHTML 和 textContent。 Then I found this jsperf test that indicates the firstChild.nodeValue is significantly faster.然后我发现这个 jsperf 测试表明 firstChild.nodeValue 明显更快。 At least that's what I interpret it to mean.至少我是这么理解的。

If firstChild.nodeValue is so much faster, what's the catch?如果 firstChild.nodeValue 快得多,有什么收获? Is it not widely supported?它不是得到广泛支持吗? Is there some other issue?还有其他问题吗?

Differences between textContent/innerText/innerHTML on MDN. MDN 上 textContent/innerText/innerHTML 之间的差异。

And a Stackoverflow answer about innerText/nodeValue. 以及关于innerText/nodeValue 的Stackoverflow 答案。

Summary概括

  1. innerHTML parses content as HTML, so it takes longer. innerHTML将内容解析为 HTML,因此需要更长的时间。
  2. nodeValue uses straight text, does not parse HTML, and is faster. nodeValue使用纯文本,不解析 HTML,速度更快。
  3. textContent uses straight text, does not parse HTML, and is faster. textContent使用直接文本,不解析 HTML,并且速度更快。
  4. innerText Takes styles into consideration. innerText考虑样式。 It won't get hidden text for instance.例如,它不会获得隐藏文本。

innerText didn't exist in firefox until FireFox 45 according to caniuse but is now supported in all major browsers.根据caniuse,在 FireFox 45 之前,firefox 中不存在innerText ,但现在所有主要浏览器都支持。

.textContent outputs text/plain while .innerHTML outputs text/html . .textContent输出text/plain.innerHTML输出text/html

Quick example:快速示例:

var example = document.getElementById('exampleId');

example.textContent = '<a href="https://google.com">google</a>';

output: <a href="http://google.com">google</a>输出:<a href="http://google.com">google</a>

example.innerHTML = '<a href="https://google.com">google</a>';

output: google输出:谷歌

You can see from the first example that output of type text/plain is not parsed by the browser and results in the full content displaying.您可以从第一个示例中看到,类型text/plain输出没有被浏览器解析并导致显示完整内容。 Output of the type text/html tells the browser to parse it before displaying it. text/html类型的输出告诉浏览器在显示之前解析它。

MDN innerHTML , MDN textContent ,MDN nodeValue MDN innerHTML , MDN textContent ,MDN nodeValue

The two I know well and work with are innerHTML and textContent .我熟悉并与之合作的两个是 innerHTML 和textContent

I use textContent when I just want to change the text of a paragraph or heading like so:当我只想像这样更改段落或标题的文本时,我使用textContent

 var heading = document.getElementById('heading') var paragraph = document.getElementById('paragraph') setTimeout(function () { heading.textContent = 'My New Title!' paragraph.textContent = 'My second <em>six word</em> story.' }, 2000)
 em { font-style: italic; }
 <h1 id="heading">My Title</h1> <p id="paragraph">My six word story right here.</p>

So, textContent just changes the text, but it doesn't parse HTML, as we can tell from the tags visible in plain text in the result there.因此, textContent只是更改文本,但它不会解析 HTML,正如我们可以从结果中纯文本中可见的标签看出的那样。

If we want to parse HTML, we use innerHTML like this:如果我们想解析 HTML,我们可以像这样使用innerHTML

 var heading = document.getElementById('heading') var paragraph = document.getElementById('paragraph') setTimeout(function () { heading.innerHTML = 'My <em>New</em> Title!' paragraph.innerHTML = 'My second <em>six word</em> story.' }, 2000)
 em { font-style: italic; }
 <h1 id="heading">My Title</h1> <p id="paragraph">My six word story right here.</p>

So, that second example parses the string I assign to the DOM element's innerHTML property as HTML.因此,第二个示例将我分配给 DOM 元素的innerHTML属性的字符串解析为 HTML。

This is awesome, and a big security vulnerability : )这太棒了,而且是一个很大的安全漏洞:)

(look up XSS if you want to know about security for this) (如果您想了解安全性,请查找 XSS)

innerText is roughly what you would get if you selected the text and copied it.如果您选择文本并复制它,则innerText大致是您将获得的内容。 Elements that are not rendered are not present in innerText.未呈现的元素不存在于innerText 中。

textContent is a concatenation of the values of all TextNodes in the sub-tree. textContent是子树中所有TextNode 的值的串联。 Whether rendered or not.无论是否渲染。

Here is a great post detailing the differences这是一篇很好的文章,详细说明了差异

innerHTML should not be included in a comparison with innerText or textContent, as it is totally different, and you should really know why:-) Look it up separately innerHTML不应与innerText 或textContent 进行比较,因为它们完全不同,您应该真正知道原因:-) 单独查找

[Note: this post is more about sharing a specific data that might help someone than telling people what to do] [注意:这篇文章更多的是关于分享可能对某人有帮助的特定数据,而不是告诉人们该做什么]

In case someone is wondering what's the fastest today: https://jsperf.com/set-innertext-vs-innerhtml-vs-textcontent & https://jsperf.com/get-innertext-vs-innerhtml-vs-textcontent (for the second test, the span's content is plain text, results might change according to its content)如果有人想知道今天最快的是什么: https : //jsperf.com/set-innertext-vs-innerhtml-vs-textcontent & https://jsperf.com/get-innertext-vs-innerhtml-vs-textcontent (对于第二个测试,span 的内容是纯文本,结果可能会根据其内容而变化)

It seems that .innerHtml is the great winner in terms of pure speed!看来.innerHtml是纯粹速度方面的大赢家!

(NOTE: I'm only talking about speed here, you might want to look for others criteria before choosing which one to use!) (注意:我在这里只讨论速度,在选择使用哪个标准之前,您可能需要寻找其他标准!)

Element.innerHTML property to set , or get element's HTML code.用于setget元素的 HTML 代码的 Element.innerHTML 属性。

Ex: We have a <h1> tag and strong style with it:例如:我们有一个<h1>标签和它的强风格:

<h1 id="myHeader" style="color: green"><strong>My Header</strong> Normal Text</h1> To get content of the element has id equals to "myHeader", we will do the same: <h1 id="myHeader" style="color: green"><strong>My Header</strong> Normal Text</h1>get id 等于“myHeader”的元素的内容,我们将执行相同的操作:

var element = document.getElementById("myHeader");
element.innerHTML

Return result:返回结果:

<strong>My Header</strong> Normal Text`

To "set" new content (value) for this element, the code will be here:要为此元素“设置”新内容(值),代码将在此处:

Element.innerHTML = "My Header My Text";

So this property not only works with plain text, but it is aimed at passing or copying HTML code.因此,此属性不仅适用于纯文本,而且旨在传递或复制 HTML 代码。

=> We should not use it. => 我们不应该使用它。

However, many programmers (including myself) use this attribute to insert text into a web page, and this method carries a potential risk:但是,很多程序员(包括我自己)使用这个属性在网页中插入文本,这种方法存在潜在的风险:

  1. Wrong operation: inserting each text only sometimes deletes all other HTML code of the inserted element.错误操作:插入每个文本有时会删除插入元素的所有其他 HTML 代码。
  2. For security: Of course, the two examples above are completely harmless, even if using the tag is still no problem because the HTML5 standard has prevented the execution of the command line inside the tag.为了安全:当然,上面两个例子是完全无害的,即使使用标签也没有问题,因为HTML5标准已经阻止了标签内部命令行的执行。 when inserted into the web page via the innerHTML attribute.当通过innerHTML 属性插入网页时。 See this rule here . 在此处查看此规则。

Because of this reason, using innerHTML is not recommended when inserting plain text, instead use textContent .由于这个原因,在插入纯文本时不建议使用innerHTML ,而是使用textContent The textContent property will not understand that the code you pass is an HTML syntax, but just a 100% text no more and no less. textContent属性不会理解您传递的代码是 HTML 语法,而只是 100% 文本,不多也不少。

The result returns if using textContent in the above example:如果在上面的示例中使用textContent返回结果:

My Header My Text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM