Web & performance

textContent vs innerText vs innerHTML in JavaScript

Choose the right DOM property for text extraction, visible text, and markup without introducing unsafe HTML insertion.

Photorealistic editorial photo for Html Textcontent Vs Innertext
Web & performance · Practical ideas for your next build

These three DOM properties answer different questions. textContent reads textual node content, innerText approximates rendered text, and innerHTML reads or writes markup. Mixing them up can lead to unexpected whitespace, hidden text in exports, or unsafe rendering of untrusted strings.

Use textContent for node text

textContent does not require the same layout-dependent interpretation as innerText. It can include text inside hidden elements and script or style nodes, so remove unwanted nodes first when extracting article content. It does not automatically insert paragraph separators between every block element. Our HTML-to-text tool explicitly adds common line boundaries before reading the resulting text.

Use innerText when rendered behavior matters

innerText generally reflects rendered text and can account for visibility and line breaks in a displayed document. Its behavior depends on whether an element is actually rendered; a detached element is not a reliable substitute for a live layout measurement. Reading it may require layout work. For a server-side or inert-document extraction pipeline, define structural rules rather than assuming browser-visible text can be recovered from HTML alone.

Treat innerHTML as markup

Reading innerHTML preserves tags rather than producing plain words. Writing untrusted strings through it creates an injection risk because the browser interprets markup. Use textContent or framework text interpolation when you intend to display text. If a product truly needs user-authored HTML, use a suitable sanitization policy and review the allowed elements, attributes, and URLs instead of trying to remove dangerous strings with ad hoc replacements.

Worked example

EXAMPLE
const node = document.createElement("div");
node.textContent = "<strong>Hello</strong>";
// Shows literal tags rather than bold markup.

Why are my paragraphs joined in textContent?

It combines text nodes rather than formatting the document visually. Add structural separators when building a plain-text export.

Reference and further reading

Read the official documentation ↗