CKTIS / JavaScript
HTML text escaping versus structural allowlist sanitization
Escape characters to display input as literal text. To preserve selected formatting, sanitize the parsed HTML structure using an explicit policy for elements and attributes.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
element.textContent = input;
element.setHTML(input, { sanitizer: { elements: ["strong"], attributes: [], comments: false, dataAttributes: false } });HTML text escaping versus structural allowlist sanitization is a choice about what the input is allowed to become. For untrusted input inserted into ordinary text in HTML source, encode for that context: for example, map & to & and < to <. The parser reads those references as text characters, not tag syntax. When working directly with the DOM, assign the raw value to textContent on an element such as a div: this replaces its contents with text without parsing HTML. HTML text escaping is not a general defense for attributes, URLs, JavaScript, or CSS.
When users should be able to keep formatting, sanitize structurally. setHTML() parses in the destination element's context, enforces the element and attribute allowlist, and removes XSS-unsafe constructs even if the configuration permits them. The example's policy allows strong but no attributes. Filter the parsed structure rather than stripping tags with a regular expression. If your policy allows links, decide separately which URLs your application accepts.
textContent and setHTML() are web-platform APIs, not ECMAScript 2024 features. Check setHTML() support in your target browsers. If it is missing, use plain text or a vetted HTML sanitizer; do not pass raw input to innerHTML. Do not assume the serialized result is safe to reparse in another context either: sanitize at insertion into the destination element.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML text escaping and structural sanitization</title>
</head>
<body>
<pre id="output"></pre>
<script>
const input = '<strong title="label">A & B</strong><br>';
const text = document.createElement('div');
const rich = document.createElement('div');
if (typeof rich.setHTML !== 'function') {
throw new Error('This example requires a browser that supports Element.setHTML().');
}
text.textContent = input;
rich.setHTML(input, {
sanitizer: {
elements: ['strong'],
attributes: [],
comments: false,
dataAttributes: false,
},
});
document.getElementById('output').textContent =
[text.innerHTML, rich.innerHTML].join('\n');
</script>
</body>
</html>Result
<strong title="label">A &amp; B</strong><br> <strong>A & B</strong>
The first line serializes literal text: even the input's `&` spelling is preserved as text. The second shows a real `strong` element with no `title` attribute and no `br` element. The example only reads `innerHTML`.
Related lessons
- JavaScript · Lesson 16 · Advanced · Version: 4