Skip to content
UniCircle
MediumConceptualDOM

innerHTML vs textContent

Question JS-DOM-002

What is the difference between innerHTML and textContent? Why is setting innerHTML with user input dangerous?

Show the explanation

Model answer.

  • `textContent` gets or sets the plain text of an element. Anything you assign is shown literally; tags are not parsed.
  • `innerHTML` gets or sets the element's content as HTML. Assigned strings are parsed into elements.
JavaScript
const comment = '<img src=x onerror="stealCookies()">';
box.textContent = comment;   // shows the characters, harmless
box.innerHTML = comment;     // creates an img; its onerror runs: XSS

Setting innerHTML with untrusted text is a cross-site scripting (XSS) hole: an attacker's markup runs with your page's privileges.

Guidelines:

  • Use textContent (or createElement + textContent) for user data.
  • If you truly need HTML from users, sanitise it with a vetted library first.
  • innerHTML also re-creates all child nodes, which drops event listeners and is slower for frequent updates.
  • innerText is similar to textContent but respects CSS (hidden text is skipped) and triggers layout, so it is slower.

Original UniCircle question. Last reviewed 22 Oct 2026.