小编典典

textContent 与 innerText 之间的区别

javascript

textContentJavaScript和JavaScript有什么区别innerText

我可以使用textContent如下:

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

阅读 221

收藏
2022-03-29

共1个答案

小编典典

您可以在下面找到摘要:textContent

  1. innerText是非标准的,textContent是较早标准化的。
  2. innerText返回节点中包含的可见textContent文本,同时返回全文。例如,在以下 HTML<span>Hello <span style="display: none;">World</span></span>中,innerText将返回“Hello”,而textContent将返回“Hello World”。
  3. 因此,innerText它对性能的要求更高:它需要布局信息才能返回结果。
  4. innerText只为HTMLElement对象textContent定义,而为所有Node对象定义。

请务必查看此答案下方的信息性评论。

textContent在 IE8 中不可用,并且裸机 polyfill 看起来像是nodeValue在所有childNodes指定节点上使用的递归函数:

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;
}
2022-03-29