Safe DOM Manipulation
By the end of this lesson you will be able to pick a safe API for every common DOM job, decide which attributes may hold user data, accept only http: and https: links, sanitise rich HTML with DOMPurify or the built-in setHTML(), build a comment list that stays safe with hostile input, and make a linter catch unsafe code for you.
What you should know first: HTML Injection & DOM-Based XSS showed how sources reach sinks. Template Element, Advanced DOM Integration and URL & URLSearchParams API cover the tools this lesson relies on. Next, Trusted Types Fundamentals makes the browser enforce these habits.
The rule: structure from code, data as text
Think of a railway reservation form. The printed form decides where the name, age and berth go. The passenger only writes inside the boxes. Even if Rohan writes "CANCEL ALL TICKETS" in the name box, the clerk reads it as a strange name, not an order.
Safe DOM code works the same way. Your code creates the elements, which is the printed form. User data only goes into text and into a few checked attribute values, which are the boxes. Nothing a user types is ever parsed as markup.
Safe APIs for everyday jobs
| Job | Safe API | Avoid |
|---|---|---|
| Show text | el.textContent = value, el.append(value) | innerHTML |
| Build elements | document.createElement(), append(), prepend(), before(), after() | HTML strings |
| Replace all children | el.replaceChildren(a, b) | el.innerHTML = "" then strings |
| Copy a structure | template.content.cloneNode(true) | Template literals with data inside |
| Set a form value | input.value = value | setAttribute("value", ...) on markup strings |
| React to events | addEventListener() | setAttribute("onclick", ...) |
| Change styles | classList, el.style.setProperty() with fixed property names | A user-controlled style attribute |
| Store data | el.dataset.orderId = value | Data inside inline script code |
Two details are worth knowing. First, append() and replaceChildren() turn a plain string argument into a text node, so li.append("<b>hi</b>") shows the tags as text. Second, textContent is faster than innerText for writing, because innerText depends on CSS and can force a layout. Both are safe.
Attributes: some are boxes, some are doors
Most attributes are just text: id, class, title, alt, lang, aria-label and any data-* attribute. A user value there cannot run code.
A few attributes are doors into code or other documents:
- Event handlers: every
on*attribute, such asonclickoronerror, is JavaScript. - URL attributes:
href,src,action,formaction,poster,dataon<object>. Ajavascript:URL runs code when followed, and adata:URL can show a whole fake page. srcdoc: a full HTML document for an iframe.style: CSS cannot run JavaScript in today's browsers, but it can cover the page with a fake layer or load images from other sites.
A small helper can enforce this. It allows a fixed list of plain attributes, checks URL attributes, and refuses everything else.
Step 1: an attribute gatekeeper
The URL check parses the value with the URL parser against document.baseURI and accepts only http: and https:. Parsing matters: the parser removes tabs and line breaks and lowercases the scheme, so tricks like java + tab + script: or JAVASCRIPT: are caught.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Attribute gatekeeper</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
table { border-collapse: collapse; }
td, th { border: 1px solid #ccc; padding: 4px 8px; text-align: start; font-size: 0.9rem; }
.no { color: #b71c1c; font-weight: bold; }
.yes { color: #1b5e20; font-weight: bold; }
</style>
</head>
<body>
<h1>Profile card for Ananya, Lucknow</h1>
<table>
<thead><tr><th>Attribute</th><th>Value from user</th><th>Result</th></tr></thead>
<tbody id="rows"></tbody>
</table>
<p id="card"></p>
<script>
const PLAIN = new Set(["id", "class", "title", "alt", "lang"]);
const URL_ATTRS = new Set(["href", "src"]);
function safeHttpUrl(value) {
const url = URL.parse(value, document.baseURI);
return url && (url.protocol === "https:" || url.protocol === "http:") ? url.href : null;
}
// Returns true if the attribute was set
function setSafeAttribute(el, name, value) {
name = name.toLowerCase();
if (PLAIN.has(name) || name.startsWith("data-") || name.startsWith("aria-")) {
el.setAttribute(name, value);
return true;
}
if (URL_ATTRS.has(name)) {
const url = safeHttpUrl(value);
if (url) { el.setAttribute(name, url); return true; }
}
return false; // on*, style, srcdoc, formaction... are refused
}
const link = document.createElement("a");
link.textContent = "Ananya's website";
const attempts = [
["title", 'Says "hello" <b>loudly</b>'],
["data-city", "Lucknow"],
["href", "https://ananya.example.in/blog"],
["href", "JAVASCRIPT:document.title='hacked'"],
["href", "java\tscript:document.title='hacked'"],
["href", "data:text/html,<h1>Fake bank login</h1>"],
["onclick", "document.title='hacked'"],
["style", "position:fixed;inset:0;background:white"]
];
for (const [name, value] of attempts) {
const ok = setSafeAttribute(link, name, value);
const tr = document.createElement("tr");
const result = document.createElement("td");
result.className = ok ? "yes" : "no";
result.textContent = ok ? "set" : "refused";
for (const text of [name, value]) {
const td = document.createElement("td");
td.textContent = text;
tr.append(td);
}
tr.append(result);
document.querySelector("#rows").append(tr);
}
document.querySelector("#card").append("Final link: ", link);
</script>
</body>
</html>You should see "set" for title, data-city and the https: link, and "refused" for the two javascript: tricks, the data: page, onclick and style. The title keeps its quotes and tags as plain text, which is correct. The final link points to Ananya's blog. If you also want to stop links to other sites, compare url.host with an allow-list of hosts.
Templates give you safe structure
When a card has many parts, building it with ten createElement() calls gets long. A <template> holds the structure as real HTML written by you, and your code fills only the boxes:
<template id="comment-tpl">
<article class="comment">
<h3 class="who"></h3>
<time class="when"></time>
<div class="body"></div>
</article>
</template>const tpl = document.querySelector("#comment-tpl");
const card = tpl.content.cloneNode(true);
card.querySelector(".who").textContent = comment.name; // a box
card.querySelector(".when").textContent = comment.date; // a box
list.append(card);The template is written by your team, so it is trusted. The data never touches a parser. This is the pattern React, Vue and Lit use internally, which is why they are safe by default until you use an escape hatch such as dangerouslySetInnerHTML or v-html.
Rich text: sanitise, do not escape
Sometimes users need formatting, such as bold text or links in a comment. Showing the tags as text would be wrong, and innerHTML would be dangerous. You need a sanitiser: a parser that keeps an allow-list of harmless elements and attributes and removes the rest.
DOMPurify (version 3.4.18 on npm when this lesson was checked, November 2026) is the common choice. Configure the smallest allow-list that works, and use a hook to make every surviving link safe:
import DOMPurify from "dompurify";
DOMPurify.addHook("afterSanitizeAttributes", (node) => {
if (node.tagName === "A") {
node.setAttribute("rel", "ugc nofollow noopener");
node.setAttribute("target", "_blank");
}
});
const clean = DOMPurify.sanitize(userHtml, {
ALLOWED_TAGS: ["p", "br", "b", "strong", "i", "em", "a", "ul", "ol", "li"],
ALLOWED_ATTR: ["href"],
ALLOWED_URI_REGEXP: /^https?:/i // only http and https links
});
commentBody.innerHTML = clean;Browsers also have a built-in sanitiser. el.setHTML(html) parses the string and always removes scripts, event handler attributes and javascript: URLs, even if your configuration asks for them. You can narrow it further:
commentBody.setHTML(userHtml, {
sanitizer: { elements: ["p", "br", "b", "i", "a"], attributes: ["href"] }
});Three rules apply to any sanitiser:
- Sanitise last. Insert the result straight away. If you change the clean HTML afterwards, for example by adding strings, you can undo the cleaning.
- Sanitise on the server too. Attackers can skip your page and post raw HTML to your API. Cross-Site Scripting (XSS) Prevention names a PHP option.
- Never write your own with regular expressions. HTML parsing has too many surprises.
Step 2: a safe comment renderer
Kabir's cricket blog in Rohtak shows reader comments with a name, an optional website and a short body that may use <b>, <i> and links. Some comments below are hostile. If any injected code runs, a red banner appears.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Safe comments</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; max-width: 40rem; }
#alarm { display: none; background: #c62828; color: white; padding: 8px; }
body.hacked #alarm { display: block; }
.comment { border-bottom: 1px solid #ddd; padding: 8px 0; }
.who { margin: 0; font-size: 1rem; }
.note { color: #666; font-size: 0.85rem; }
</style>
</head>
<body>
<p id="alarm">INJECTED: a comment ran code on this page</p>
<h1>Rohtak Cricket Blog: comments</h1>
<p id="mode" class="note"></p>
<section id="list"></section>
<template id="comment-tpl">
<article class="comment">
<h2 class="who"></h2>
<div class="body"></div>
<p class="note"></p>
</article>
</template>
<script>
const comments = [
{ name: "Priya", site: "https://priya.example.in/", body: "What a <b>last over</b> by our captain!" },
{ name: '<img src="data:," onerror="document.body.classList.add(\'hacked\')">', site: "", body: "Nice post" },
{ name: "Farhan", site: "javascript:document.body.classList.add('hacked')", body: "Click my name!" },
{ name: "Isha", site: "", body: 'See <a href="javascript:document.body.classList.add(\'hacked\')">scores</a> and <a href="https://scores.example.in/">real scores</a> <i onmouseover="document.body.classList.add(\'hacked\')">hover me</i>' }
];
const canSanitise = "setHTML" in Element.prototype;
document.querySelector("#mode").textContent = canSanitise
? "Formatting kept with the built-in setHTML() sanitiser."
: "setHTML() is not available here, so formatting is shown as plain text.";
function safeHttpUrl(value) {
const url = URL.parse(value, document.baseURI);
return url && (url.protocol === "https:" || url.protocol === "http:") ? url.href : null;
}
function renderComment(c) {
const card = document.querySelector("#comment-tpl").content.cloneNode(true);
const who = card.querySelector(".who");
const site = c.site ? safeHttpUrl(c.site) : null;
if (site) {
const a = document.createElement("a");
a.href = site;
a.rel = "ugc nofollow noopener";
a.textContent = c.name;
who.append(a);
} else {
who.textContent = c.name;
}
const body = card.querySelector(".body");
if (canSanitise) {
body.setHTML(c.body, { sanitizer: { elements: ["b", "i", "a"], attributes: ["href"] } });
for (const a of body.querySelectorAll("a")) {
const raw = a.getAttribute("href");
const href = raw ? safeHttpUrl(raw) : null; // the sanitiser may have removed it
if (href) { a.href = href; a.rel = "ugc nofollow noopener"; }
else a.removeAttribute("href");
}
} else {
body.textContent = c.body;
}
card.querySelector(".note").textContent = c.site && !site ? "Website removed: not an http or https address" : "";
return card;
}
document.querySelector("#list").replaceChildren(...comments.map(renderComment));
</script>
</body>
</html>In Chrome, Edge or Firefox you should see four comments and no red banner, even after hovering everywhere:
- Priya's name is a link to her site, and "last over" is bold.
- The second name shows the whole
<img ...>text, because names are always text. - Farhan's name is plain text with the note "Website removed".
- Isha's "scores" link has no address, the real scores link works, and "hover me" is italic with its handler stripped.
In Safari, comment bodies appear as plain text, which is safe but less pretty. In a real project, the fallback would be DOMPurify.
Let the linter watch your back
Code reviews miss things. Mozilla's eslint-plugin-no-unsanitized (version 4.1.5, with ESLint 10.15, checked November 2026) flags writes to innerHTML, outerHTML, insertAdjacentHTML(), document.write() and similar sinks when the value is not a plain constant. ESLint's own rules catch string eval. A flat config file:
// eslint.config.js
import globals from "globals";
import nounsanitized from "eslint-plugin-no-unsanitized";
export default [
nounsanitized.configs.recommended,
{
languageOptions: { globals: globals.browser },
rules: {
"no-eval": "error",
"no-implied-eval": "error",
"no-new-func": "error",
"no-script-url": "error"
}
}
];Run on this file:
const box = document.querySelector("#comments");
const name = new URLSearchParams(location.search).get("name");
box.innerHTML = "<p>Hello " + name + "</p>";
box.insertAdjacentHTML("beforeend", `<p>${name}</p>`);
box.innerHTML = "<p>Static text is fine</p>";
box.textContent = name;
setTimeout("refresh()", 1000);npx eslint src/comments.js reports (path line omitted):
4:1 error Unsafe assignment to innerHTML (Variable 'name' initialized with unsafe value at 2:13) no-unsanitized/property 5:1 error Unsafe call to box.insertAdjacentHTML for argument 1 (Variable 'name' initialized with unsafe value at 2:13) no-unsanitized/method 8:1 error Implied eval. Consider passing a function instead of a string no-implied-eval ✖ 3 problems (3 errors, 0 warnings)
The constant string on line 6 and the textContent line pass. The plugin also accepts calls to setHTML(). Run the linter in your editor and in CI, as Automated HTML Validation shows, so unsafe code cannot be merged quietly.
Common mistakes
- Escaping by hand with
replace()and then usinginnerHTML. One missed character or context breaks it. - Checking URLs with
startsWith("http").httpevil:passes, and uppercase or whitespace tricks slip through. Parse withURL. - Allowing
styleoron*through a genericsetAttribute()helper. - Modifying sanitised HTML before inserting it.
- Using
setHTMLUnsafe()because it sounds similar tosetHTML(). It is a sink.
Interview questions
1. Why is textContent safe but innerHTML not?
textContent always creates a single text node, so < and > are just characters. innerHTML runs the HTML parser, which creates elements and attributes, including event handlers such as onerror that run code. Use innerHTML only with trusted constants or sanitised HTML.
2. How do you safely put a user-supplied URL in href?
Parse it with new URL() or URL.parse() against a base, then accept it only if the protocol is http: or https:. Set the parsed href, not the raw string. For stricter control, also check the host against an allow-list.
3. When do you need a sanitiser instead of escaping?
When users must be able to use some formatting, such as bold text and links. Escaping would show the tags as text. A sanitiser parses the HTML and keeps only allowed elements and attributes, removing scripts, handlers and dangerous URLs.
4. What is the difference between setHTML() and setHTMLUnsafe()?
setHTML() sanitises the input and always removes script-capable content, even with a custom configuration. setHTMLUnsafe() parses without sanitising, so it is as dangerous as innerHTML. In November 2026, setHTML() works in Chromium and Firefox but not Safari.
5. How can tooling prevent unsafe DOM code?
A linter plugin such as eslint-plugin-no-unsanitized flags writes to innerHTML and calls like insertAdjacentHTML() with non-constant values, and ESLint core rules flag eval and string timers. Running it in CI stops such code from being merged. Trusted Types then enforce the same rule in the browser.
Key points
- Structure comes from your code or templates; user data goes in only as text or checked attribute values.
textContent,append(),replaceChildren()andcreateElement()cover most jobs without any parser.- Plain attributes are safe;
on*, URL attributes,srcdocandstyleneed rules or refusal. - Validate URLs by parsing them and allowing only
http:andhttps:. - For rich text, sanitise with DOMPurify or
setHTML()(no Safari yet), sanitise last, and sanitise on the server too. - eslint-plugin-no-unsanitized and ESLint's eval rules catch unsafe sinks before review.
Exercise
Ananya runs a recipe site in Pune. Write a renderRecipe(recipe) function for objects like { title, sourceUrl, imageUrl, tags: [] } where every field comes from users. It must return an <article> with the title in an <h2>, an image whose src is used only if it is an https: address (with the title as alt), a "Source" link only for http: or https: URLs, and the tags as <li> items. Do not use innerHTML, insertAdjacentHTML() or template literals with user data.
Show solution
function parseUrl(value, schemes) {
if (!value) return null; // an empty string would resolve to the page itself
const url = URL.parse(value, document.baseURI);
return url && schemes.includes(url.protocol) ? url.href : null;
}
function renderRecipe(recipe) {
const article = document.createElement("article");
const h2 = document.createElement("h2");
h2.textContent = recipe.title;
article.append(h2);
const img = parseUrl(recipe.imageUrl, ["https:"]);
if (img) {
const el = document.createElement("img");
el.src = img;
el.alt = recipe.title;
article.append(el);
}
const source = parseUrl(recipe.sourceUrl, ["http:", "https:"]);
if (source) {
const a = document.createElement("a");
a.href = source;
a.rel = "ugc nofollow noopener";
a.textContent = "Source";
article.append(a);
}
const ul = document.createElement("ul");
ul.replaceChildren(...(recipe.tags ?? []).map((tag) => {
const li = document.createElement("li");
li.textContent = tag;
return li;
}));
article.append(ul);
return article;
}Every user value goes through textContent, alt or a parsed and scheme-checked URL. An empty or invalid image address simply means no image, and a javascript: source means no link.
Quick Quiz
1. What does li.append("<b>Pune</b>") show?
append() turns a string into a text node, so no markup is created.
2. Which check correctly blocks JAVASCRIPT:alert(1) in a link?
The parser lowercases the scheme and strips tabs and line breaks, and an allow-list rejects everything else.
3. Which of these is a sink that does NOT sanitise?
setHTMLUnsafe() parses HTML without sanitising, like innerHTML.
4. A sanitiser returned clean HTML. What should you avoid next?
Changing sanitised HTML can reintroduce unsafe markup; sanitise as the last step.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
