JavaScript Interview Question #56

What is the difference between innerHTML and textContent?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

innerHTML reads or writes HTML markup inside an element, so assigned markup is parsed into DOM nodes. textContent reads or writes plain text and does not interpret HTML tags.

Detailed Explanation

innerHTML reads or writes HTML markup inside an element, so assigned markup is parsed into DOM nodes. textContent reads or writes plain text and does not interpret HTML tags.

Use textContent for ordinary user-controlled text. Assigning untrusted content to innerHTML can create cross-site scripting vulnerabilities unless the content is properly sanitized with a suitable security strategy.

Code Example

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

message.textContent = "<strong>Safe text</strong>";
// Displays the angle brackets as text.

// Use innerHTML only with trusted/safely sanitized markup.
message.innerHTML = "<strong>Trusted markup</strong>";