HTML Injection Prevention and Safe DOM Insertion
Treat untrusted input as text
Cross-site scripting (XSS) occurs when untrusted data is interpreted as executable page content. When displaying comments or names, assign textContent to a normal text container. This harmless string resembles markup but remains literal text.
<p id="comment"></p><script> document.querySelector("#comment").textContent = "<strong>Hello</strong>";</script>The literal tags appear as text.
Build trusted structure explicitly
Create elements using fixed tag names and insert the untrusted value as text. The browser parses innerHTML as markup; do not concatenate input into it. If rich HTML is required, use a maintained sanitizer configured for the intended content and review its output contexts.
<ul id="comments"></ul><script> const item = document.createElement("li"); item.textContent = "A & B"; document.querySelector("#comments").append(item);</script>One list item contains A & B.
Validate URL destinations separately
Text insertion does not validate URLs. For this internal documentation link, parse the candidate with URL, then require both HTTPS and the expected origin before assigning href. The example uses only fixed illustrative URLs and does not navigate. Other contexts require their own defenses.
<a id="help">Help</a><script> const candidate = new URL("/help", "https://example.com"); if (candidate.protocol === "https:" && candidate.origin === "https://example.com") { document.querySelector("#help").href = candidate.href; }</script>The link receives the approved destination.
Common mistakes and practice
Avoid treating HTML escaping as universal protection. Text, attributes, URLs and script contexts differ. Prefer framework auto-escaping, safe APIs and server-side authorization; CSP is an additional layer, not a substitute. Practice rendering a name with literal angle brackets.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Injection Prevention and Safe DOM Insertion — Knowledge Check
Apply the security, privacy and performance concepts taught in this lesson.
Which API inserts literal text into a paragraph?
What is an injection sink?
What must an internal URL allowlist check?
When rich user markup is necessary, what is appropriate?
Does CSP replace safe insertion?