← 中文资源

简体中文版本

innerText 看渲染,textContent 看源码

textContent 原样拼接每个文本节点,样式表内容和隐藏 span 都在内;innerText 按渲染结果取文本,display:none 隐藏的部分不会出现。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:box。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。

常见问题

「innerText 看渲染,textContent 看源码」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

<p>Alpha <span class="gone">hidden</span> Beta</p>
</div>
`;
const box = document.querySelector("#box");

代码示例

document.body.innerHTML = `
  <div id="box">
    <style>.gone { display: none; }</style>
    <p>Alpha <span class="gone">hidden</span> Beta</p>
  </div>
`;

const box = document.querySelector("#box");

// textContent reads every text node in the tree, including
// the style sheet text and the display:none span
console.log(box.textContent.includes(".gone"));   // true
console.log(box.textContent.includes("hidden"));  // true

// innerText approximates rendered text: what CSS hides
// does not appear
console.log(box.innerText.includes(".gone"));     // false
console.log(box.innerText.includes("hidden"));    // false