Spot innerHTML vs textContent Issue
Question
This code displays user input but has a security risk. What is wrong?
Code
const userInput = "<img src=x onerror=alert('xss')>";
const el = document.getElementById("output");
el.innerHTML = userInput;
Hint
innerHTML interprets HTML; textContent treats input as plain text.
Explanation
Setting innerHTML with untrusted user input allows HTML injection (XSS — Cross-Site Scripting). The malicious input injects an <img> tag with an onerror handler that runs JavaScript. The fix is to use el.textContent = userInput, which treats the input as plain text and displays it literally without executing any HTML or scripts.
Related Resources
Related Lessons
- DOM
Learn about innerHTML vs textContent.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.