textContent Keeps Untrusted Strings Inert

textContent stores untrusted text as one inert text node, while the same string through innerHTML is parsed as markup and handler attributes come alive.

JavascriptSecurity Boundaries

Code

javascriptsnippet
19 lines
// comment.body comes from an untrusted source: the same string through two rendering paths produces completely different results
const comment = { author: 'ada', body: '<img src=x onerror="steal()">hi' };

// innerHTML: the string enters the HTML parser and <img onerror> becomes a real element with a real attribute
const unsafe = document.createElement('p');
unsafe.innerHTML = '<b>' + comment.author + '</b>: ' + comment.body;
console.log('innerHTML parsed elements:', unsafe.querySelectorAll('*').length);

// createElement + textContent: the text never reaches the parser, so markup shows up literally
const safe = document.createElement('p');
const label = document.createElement('b');
label.textContent = comment.author;
safe.append(label, ': ', comment.body); // append treats string arguments as text nodes
console.log('safe child nodes:', safe.childNodes.length);
console.log('elements inside safe:', safe.querySelectorAll('*').length);
console.log('visible text:', safe.textContent);

// double-check: no element inside safe carries an onerror attribute
console.log('handlers in safe:', safe.querySelectorAll('[onerror]').length);

What the code does

Module-level bindings hold the data — comment, unsafe, safe, label — with no function scope in between.

The top-level object literal pins author, body as plain values — no derivation, no imports behind them.

What to watch for

  • A browser is the runtime here: document are not available in Node.

Applying it

The demo output is labeled (innerHTML parsed elements:, safe child nodes:, elements inside safe:), so every printed line maps back to its originating operation.

Statements that matter

safe.append(label, ': ', comment.body); // append treats string arguments as text nodes
console.log('safe child nodes:', safe.childNodes.length);
const comment = { author: 'ada', body: '<img src=x onerror="steal()">hi' };
unsafe.innerHTML = '<b>' + comment.author + '</b>: ' + comment.body;

Interactive Tools for This Topic

FAQ

Does textContent Keeps Untrusted Strings Inert 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.