Prevent script injection with safe DOM construction
Quick answer
Cross-site scripting (XSS) occurs when untrusted content is interpreted as executable browser content in a trusted application. For plain labels or messages, build elements with DOM methods and assign textContent instead of parsing input as markup.
How it works
Use createElement with a developer-chosen element name and textContent for user text. A text node is not an HTML parser. If the product really needs rich HTML, use a maintained, context-appropriate sanitizer and avoid unsafe transformations after sanitization. Different contexts such as URLs and script text need distinct controls. Do not infer safety from the absence of a visible script tag. The examples contain harmless markup-like text only.
Local examples
Run in a fresh browser document. Actual ByteMind editor support is unverified.
(async () => {const el=document.createElement("p");el.textContent="<b>Notebook</b>";console.log(el.textContent,el.children.length);})()Expected console output:
<b>Notebook</b> 0The string stays literal and no b element is created.
Run in a fresh browser document. Actual ByteMind editor support is unverified.
(async () => {const ul=document.createElement("ul");for(const name of ["A & B","<em>C</em>"]){const li=document.createElement("li");li.textContent=name;ul.append(li);}console.log(ul.children.length,ul.querySelectorAll("em").length);})()Expected console output:
2 0Both labels become list items, and neither produces nested markup.
Common mistakes
Do not assign untrusted strings to innerHTML or assume replacing one character protects every output context.
Practice
Build a list of three user labels containing angle brackets, then verify that the labels are text and do not create nested elements.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Prevent script injection with safe DOM construction — Knowledge Check
Apply the concept and reason about local example output.
Which sink fits an untrusted plain product label?
What is needed if a feature deliberately permits rich HTML?
Why create element names in trusted code?
What is the exact console output in Prevent script injection with safe DOM construction example 1?
(async () => {const el=document.createElement("p");el.textContent="<b>Notebook</b>";console.log(el.textContent,el.children.length);})()What is the exact console output in Prevent script injection with safe DOM construction example 2?
(async () => {const ul=document.createElement("ul");for(const name of ["A & B","<em>C</em>"]){const li=document.createElement("li");li.textContent=name;ul.append(li);}console.log(ul.children.length,ul.querySelectorAll("em").length);})()