HTML Sanitizer Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓HTML Sanitizer runs in O(n) time and O(n) space, in JavaScript as in every other language.
- ✓The platform is the parser. new DOMParser().parseFromString(html, 'text/html') runs the same spec algorithm the network stack uses and yields a document with no browsing context, so nothing in it executes; document.implementation.createHTMLDocument() and a detached template element's .content are the other inert containers.
- ✓Reviewers reject any path that routes untrusted markup through innerHTML, including doing it temporarily in order to parse.
- ✓The JavaScript trap: DOM clobbering attacks the sanitizer from inside its own input. HTMLFormElement is declared [LegacyOverrideBuiltIns], so a named child shadows genuine properties: <form><input name="attributes"> makes form.attributes evaluate to that input element rather than a NamedNodeMap.
- ✓Parsing materialises a full DOM: a native node plus a JavaScript wrapper for every element, attribute and text run, all of it main-thread garbage the moment you return the string.
What HTML Sanitizer actually is
HTML Sanitizer in JavaScript: what you actually reach for
JavaScript implementation
const ALLOWED = new Map([
["p", []], ["em", []], ["code", []], ["strong", []],
["a", ["href", "hreflang"]],
]);
const SAFE_SCHEMES = new Set(["https:", "mailto:"]);
const HTML_NS = "http://www.w3.org/1999/xhtml";
// <form><input name="attributes"> clobbers el.attributes into an Element,
// because HTMLFormElement is [LegacyOverrideBuiltIns]. Capture the genuine
// accessors off the prototype now, before any untrusted node exists.
const getAttrs = Object.getOwnPropertyDescriptor(Element.prototype, "attributes").get;
const removeAttr = Element.prototype.removeAttribute;
const detach = Element.prototype.remove;
export function sanitize(fragment, base = document.baseURI) {
// Inert document: no browsing context, so nothing here runs or loads.
const doc = new DOMParser().parseFromString(fragment, "text/html");
const walk = doc.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT);
const doomed = [];
for (let el = walk.nextNode(); el; el = walk.nextNode()) {
const allowed = ALLOWED.get(el.localName);
// localName alone is ambiguous: <svg><a> and <a> both report "a".
if (!allowed || el.namespaceURI !== HTML_NS) {
doomed.push(el);
continue;
}
for (const attr of Array.from(getAttrs.call(el))) {
const name = attr.name.toLowerCase();
const bad = !allowed.includes(name) ||
(name === "href" && !isSafeUrl(attr.value, base));
if (bad) removeAttr.call(el, attr.name);
}
}
// Removing during the walk would strand the TreeWalker's current node.
for (const el of doomed) detach.call(el);
return doc.body.innerHTML;
}
function isSafeUrl(value, base) {
try {
return SAFE_SCHEMES.has(new URL(value, base).protocol);
} catch {
return false; // no scheme and no usable base: URL() throws, so reject
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for HTML Sanitizer?
The platform is the parser. new DOMParser().parseFromString(html, 'text/html') runs the same spec algorithm the network stack uses and yields a document with no browsing context, so nothing in it executes; document.implementation.createHTMLDocument() and a detached template element's .content are the other inert containers. Traverse with document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT), read identity from localName and namespaceURI, and resolve links with the URL constructor. DOMPurify is the established library, and Trusted Types is the platform mechanism for making one function the only source of assignable markup.
What is the most common JavaScript mistake when implementing HTML Sanitizer?
DOM clobbering attacks the sanitizer from inside its own input. HTMLFormElement is declared [LegacyOverrideBuiltIns], so a named child shadows genuine properties: <form><input name="attributes"> makes form.attributes evaluate to that input element rather than a NamedNodeMap. Iterating it produces nothing, so every attribute on that form survives untouched, and <img name="getElementById"> does the same to document. Nothing throws; the loop simply finds no attributes and reports success. The defence is to call the real accessor explicitly, via Object.getOwnPropertyDescriptor(Element.prototype, 'attributes').get, which no supplied node can shadow.
How does HTML Sanitizer actually perform in JavaScript?
Parsing materialises a full DOM: a native node plus a JavaScript wrapper for every element, attribute and text run, all of it main-thread garbage the moment you return the string. A TreeWalker is the cheap traversal because it never builds a collection, whereas querySelectorAll allocates a static list of every match first. Reading body.innerHTML at the end is a second full pass that serialises the tree into one string. Note the asymmetry with the live document: nodes created here fetch nothing, while the same markup assigned to an attached element starts image requests immediately. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.