Update text safely
Quick answer
Setting textContent replaces child content with literal text. It does not interpret HTML markup. For displaying user-supplied text this avoids HTML parsing.
Browser example
Run in a browser document, not a bare Node.js process.
const box=document.createElement("div");box.textContent="<b>Hi</b>";console.log(box.textContent,box.children.length);Expected console output:
<b>Hi</b> 0Common mistake
Do not insert untrusted strings through innerHTML.
Practice
Display a user label containing angle brackets literally.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Update text safely — Knowledge Check
Check the central concept, apply it to a new scenario, and predict browser behavior.
Which property displays a string without parsing HTML?
A user label contains angle brackets. What should a text-only status display do?
A div already contains a span. What happens if you set div.textContent to 'Ready'?
Why is textContent appropriate for a user-supplied label rather than an HTML insertion sink?
What is printed by this browser snippet? (Update text safely)
const p=document.createElement("p");p.append(document.createElement("em"));p.textContent="<em>OK</em>";console.log(p.children.length,p.textContent);