Javascript textContent 与 innerText 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35213147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:24:50  来源:igfitidea点击:

Difference between textContent vs innerText

javascript

提问by J K

What is the difference between textContentand innerTextin JavaScript?

JavaScript 中textContent和之间有什么区别innerText

Can I use textContentas follows:

我可以使用textContent如下:

var logo$ = document.getElementsByClassName('logo')[0];
logo$.textContent = "Example";

回答by Tyblitz

None of the other answers succeeds in providing the full explanation, hence this one. The key differences between innerTextand textContentare outlined very well in Kelly Norton's blogpost: innerText vs. textContent. Below you can find a summary:

其他答案都没有成功提供完整的解释,因此是这个。Kelly Norton 的博文:innerText 与 textContent 中很好地概述了innerText和之间的主要区别。您可以在下面找到摘要:textContent

  1. innerTextwas non-standard, while textContentwas standardized earlier.
  2. innerTextreturns the visibletext contained in a node, while textContentreturns the fulltext. For example, on the following HTML <span>Hello <span style="display: none;">World</span></span>, innerTextwill return 'Hello', while textContentwill return 'Hello World'. For a more complete list of differences, see the table at http://perfectionkills.com/the-poor-misunderstood-innerText/(further reading at 'innerText' works in IE, but not in Firefox).
  3. As a result, innerTextis much more performance-heavy: it requires layout information to return the result.
  4. innerTextis defined only for HTMLElementobjects, while textContentis defined for all Nodeobjects.
  1. innerText是非标准的,而textContent更早的标准化。
  2. innerText返回可见包含在一个节点的文本,而textContent返回完整文本。例如,在下面的 HTML 中<span>Hello <span style="display: none;">World</span></span>innerText将返回 'Hello',而textContent将返回 'Hello World'。有关更完整的差异列表,请参阅http://perfectkills.com/the-poor-misunderstood-innerText/ 上的表格(进一步阅读“innerText”在 IE 中有效,但在 Firefox 中无效)。
  3. 因此,innerText性能更高:它需要布局信息来返回结果。
  4. innerText仅针对HTMLElement对象定义,而textContent针对所有Node对象定义。

A workaround for textContentin IE8- would involve a recursive function using nodeValueon all childNodesof the specified node, here's a try at a polyfill:

textContent在 IE8- 中的解决方法将涉及nodeValue在所有childNodes指定节点上使用的递归函数,这里尝试使用 polyfill:

function textContent(rootNode) {
  if ('textContent' in document.createTextNode(''))
    return rootNode.textContent;

  var childNodes = rootNode.childNodes,
      len = childNodes.length,
      result = '';

  for (var i = 0; i < len; i++) {
    if (childNodes[i].nodeType === 3)
      result += childNodes[i].nodeValue;
    else if (childNodes[i].nodeType === 1) 
      result += textContent(childNodes[i]);
  }

  return result;
}

回答by Martin Wantke

textContentis the only one available for text nodes:

textContent是唯一可用于文本节点的:

var text = document.createTextNode('text');

console.log(text.innerText);    //  undefined
console.log(text.textContent);  //  text

In element nodes, innerTextevaluates <br> elements, while textContentevaluates control characters:

在元素节点中,innerText评估 <br> 元素,同时textContent评估控制字符:

var span = document.querySelector('span');
span.innerHTML = "1<br>2<br>3<br>4\n5\n6\n7\n8";
console.log(span.innerText); // breaks in first half
console.log(span.textContent); // breaks in second half
<span></span>

span.innerTextgives:

span.innerText给出:

1
2
3
4 5 6 7 8

span.textContentgives:

span.textContent给出:

1234
5
6
7
8

Strings with control characters (e. g. line feeds) are not available with textContent, if the content was set with innerText. The other way (set control characters with textContent), all characters are returned both with innerTextand textContent:

textContent如果内容是用 设置的,则带有控制字符(例如换行符)的字符串不可用innerText。另一种方式(用 设置控制字符textContent),所有字符都用innerText和返回textContent

var div = document.createElement('div');
div.innerText = "x\ny";
console.log(div.textContent);  //  xy

回答by Richard Hamilton

Both innerText& textContentare standardized as of 2016. All Nodeobjects (including pure text nodes) have textContent, but only HTMLElementobjects have innerText.

两个innerText&textContent从 2016 年开始标准化。所有Node对象(包括纯文本节点)都有textContent,但只有HTMLElement对象有innerText

While textContentworks with most browsers, it does not work on IE8 or earlier. Use this polyfill for it to work on IE8 only. This polyfill will not work with IE7 or earlier.

虽然textContent适用于大多数浏览器,但它不适用于 IE8 或更早版本。使用这个 polyfill 让它只在 IE8 上工作。此 polyfill 不适用于 IE7 或更早版本。

if (Object.defineProperty 
  && Object.getOwnPropertyDescriptor 
  && Object.getOwnPropertyDescriptor(Element.prototype, "textContent") 
  && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
  (function() {
    var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
    Object.defineProperty(Element.prototype, "textContent",
     {
       get: function() {
         return innerText.get.call(this);
       },
       set: function(s) {
         return innerText.set.call(this, s);
       }
     }
   );
  })();
}

The Object.definePropertymethod is availabe in IE9 or up, however it is available in IE8 for DOM objects only.

Object.defineProperty方法在 IE9 或更高版本中可用,但在 IE8 中仅适用于 DOM 对象。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

回答by Northern

For those who googled this question and arrived here. I feel the most clear answer to this question is in MDN document: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent.

对于那些用谷歌搜索这个问题并到达这里的人。我觉得这个问题最明确的答案是在 MDN 文档中:https: //developer.mozilla.org/en-US/docs/Web/API/Node/textContent

You can forgot all the points that may confuse you but remember 2 things:

您可以忘记所有可能使您感到困惑的要点,但请记住两件事:

  1. When you are trying to alter the text, textContentis usually the property you are looking for.
  2. When you are trying to grab text from some element, innerTextapproximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard. And textContentgives you everything, visible or hidden, including <script>and <style>elements.
  1. 当您尝试更改文本时,textContent通常是您要查找的属性。
  2. 当您尝试从某个元素中抓取文本时,innerText如果用户使用光标突出显示该元素的内容,然后将其复制到剪贴板,则该文本近似于用户将获得的文本。并textContent为您提供可见或隐藏的一切,包括<script><style>元素。

回答by Jeremy Ray Brown

textContent is supported by most browsers. It is not supported by ie8 or earlier, but a polyfill can be used for this

大多数浏览器都支持 textContent。ie8 或更早版本不支持,但可以使用 polyfill

The textContent property sets or returns the textual content of the specified node, and all its descendants.

textContent 属性设置或返回指定节点及其所有后代的文本内容。

See http://www.w3schools.com/jsref/prop_node_textcontent.asp

http://www.w3schools.com/jsref/prop_node_textcontent.asp

回答by Mr Lister

Aside from all the differences that were named in the other answers, here is another one which I discovered only recently:

除了其他答案中提到的所有差异之外,这是我最近才发现的另一个差异:

Even though the innerTextproperty is said to've been standardised since 2016, it exhibits differences between browsers: Mozilla ignores U+200E and U+200F characters ("lrm" and "rlm") in innerText, while Chrome does not.

尽管innerText据说该属性自 2016 年以来已经标准化,但它显示出浏览器之间的差异:Mozilla 会忽略 中的 U+200E 和 U+200F 字符(“lrm”和“rlm”)innerText,而 Chrome 则不会。

console.log(document.getElementById('test').textContent.length);
console.log(document.getElementById('test').innerText.length);
<div id="test">[&#x200E;]</div>

Firefox reports 3 and 2, Chrome reports 3 and 3.

Firefox 报告 3 和 2,Chrome 报告 3 和 3。

Not sure yet if this is a bug (and if so, in which browser) or just one of those quirky incompatibilities which we have to live with.

尚不确定这是否是一个错误(如果是,在哪个浏览器中)或只是我们必须忍受的那些古怪的不兼容性之一。

回答by Milan Chandro

textContent returns full text and does not care about visibility, while innerText does.

textContent 返回全文并且不关心可见性,而 innerText 关心。

<p id="source">
    <style>#source { color: red; }</style>
    Text with breaking<br>point.
    <span style="display:none">HIDDEN TEXT</span>
</p>

Output of textContent:

文本内容的输出:

#source { color: red; } Text with breakingpoint. HIDDEN TEXT

Output of innerText ( note how innerText is aware of tags like <br>, and ignores hidden element ):

innerText 的输出(注意 innerText 如何知道像<br>, 和忽略隐藏元素这样的标签):

Text with breaking point.

回答by Ashwath Halemane

innerHTML will execute even the HTML tags which might be dangerous causing any kind of client-side injection attack like DOM based XSS. Here is the code snippet:

innerHTML 甚至会执行 HTML 标签,这可能会导致任何类型的客户端注入攻击,如基于 DOM 的 XSS。这是代码片段:

<!DOCTYPE html>
<html>
    <body>
        <script>
            var source = "Hello " + decodeURIComponent("<h1>Text inside gets executed as h1 tag HTML is evaluated</h1>");  //Source
            var divElement = document.createElement("div");
            divElement.innerHTML = source;  //Sink
            document.body.appendChild(divElement);
        </script>
    </body>
</html>

If you use .textContent, it will not evaluate the HTML tags and print it as String.

如果您使用 .textContent,它不会评估 HTML 标签并将其打印为字符串。

<!DOCTYPE html>
<html>
    <body>
        <script>
            var source = "Hello " + decodeURIComponent("<h1>Text inside will not get executed as HTML</h1>");  //Source
            var divElement = document.createElement("div");
            divElement.textContent = source;  //Sink
            document.body.appendChild(divElement);
        </script>
    </body>
</html>

Reference: https://www.scip.ch/en/?labs.20171214

参考:https: //www.scip.ch/en/?labs.20171214