innerText Is Layout Aware, textContent Is Not

textContent concatenates every text node including style rules and hidden spans, while innerText approximates rendered output and drops what CSS hides.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
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

The route the code takes

Top-level bindings box hold the demo state — nothing sits inside a function scope.

What to watch for

  • The environment needs no preparation beyond having the interpreter or compiler.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Core lines

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

Interactive Tools for This Topic

FAQ

Does innerText Is Layout Aware, textContent Is Not run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.