Difference Between innerHTML, textContent, and innerText

When manipulating the Document Object Model (DOM) in JavaScript, innerHTML, textContent, and innerText are three primary properties used to read or modify the contents of an HTML element. While they may appear similar at first glance, they handle HTML parsing, styling rules, hidden elements, and performance in fundamentally different ways. Understanding these differences is essential for writing secure, performant, and bug-free JavaScript code.


1. innerHTML

The innerHTML property gets or sets the HTML or XML markup contained within an element.

Example:

const element = document.getElementById('example');
element.innerHTML = '<strong>Hello World!</strong>';
// Result: Renders "Hello World!" in bold text.

2. textContent

The textContent property gets or sets the raw text content of a node and all of its descendants.

Example:

const element = document.getElementById('example');
element.textContent = '<strong>Hello World!</strong>';
// Result: Displays the literal string "<strong>Hello World!</strong>" on the page.

3. innerText

The innerText property represents the “rendered” text content of a node, mimicking what a user actually sees in the browser.


Quick Comparison

Feature innerHTML textContent innerText
Parses HTML tags? Yes No No
Returns hidden text (display: none)? Yes (as markup) Yes No
Aware of CSS/Styling? No No Yes
Performance Slower (HTML parser) Fastest Slower (triggers reflow)
XSS Risk on user input? High None None

When to Use Which