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.
const comment = '<img src=x onerror="stealCookies()">';
box.textContent = comment; // shows the characters, harmless
box.innerHTML = comment; // creates an img; its onerror runs: XSSSetting innerHTML with untrusted text is a cross-site scripting (XSS) hole: an attacker's markup runs with your page's privileges.
Guidelines:
- Use
textContent(orcreateElement+textContent) for user data. - If you truly need HTML from users, sanitise it with a vetted library first.
innerHTMLalso re-creates all child nodes, which drops event listeners and is slower for frequent updates.innerTextis similar totextContentbut respects CSS (hidden text is skipped) and triggers layout, so it is slower.
Original UniCircle question. Last reviewed 22 Oct 2026.
