DOMParser Turns HTML Strings Into Documents
Parse untrusted HTML strings with DOMParser into a detached document where scripts never run and images never load, then extract safe text.
Code
// DOMParser turns an HTML string into a detached Document. Scripts
// in the markup never execute and images never load, unlike
// innerHTML on a live element — parsing is observation only.
const untrusted =
'<img src=/x onerror=steal()><p>Review: <b onclick=navigate()>read</b> more</p>';
const doc = new DOMParser().parseFromString(untrusted, 'text/html');
// The parsed nodes exist and can be queried like any document
console.log(doc.querySelector('p').textContent);
// Event handler attributes are parsed as data, never dispatched
const img = doc.querySelector('img');
console.log(img.hasAttribute('onerror'));
// Move only trusted text into the live DOM
const safe = document.createElement('p');
safe.textContent = doc.querySelector('p').textContent;
document.body.append(safe);Parsing as observation, not execution
new DOMParser().parseFromString(untrusted, 'text/html') turns the string '<img src=/x onerror=steal()><p>Review: <b onclick=navigate()>read</b> more</p>' into a detached Document: scripts in the markup never execute and images never load, unlike innerHTML on a live element. The handler attributes still exist as data — img.hasAttribute('onerror') returns true on the parsed node — but nothing ever dispatches them.
Extracting only trusted text
doc.querySelector('p').textContent yields the paragraph’s text, and the demo moves exactly that string into the live DOM via safe.textContent = … before document.body.append(safe). That is the transfer point: nodes from the inert document stay there, and only plain text crosses over.
The line that isolates the string
const doc = new DOMParser().parseFromString(untrusted, 'text/html');
Everything queried afterwards (doc.querySelector('p'), doc.querySelector('img')) reads from this detached document, so the hostile markup in untrusted never gets a chance to run inside the page.
Interactive Tools for This Topic
FAQ
- Does DOMParser Turns HTML Strings Into Documents run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.