textContent versus innerHTML and XSS
Lesson 7 of 38 in the JavaScript learning path.
When is innerHTML dangerous, and what should I use instead?
textContent reads and writes the text of a node. The characters are shown as text, so a less-than sign stays a less-than sign. innerHTML is different: the string is parsed as HTML and the resulting nodes replace the children of the element. That parse is useful only for markup you trust completely, and a student name or comment is not in that set. If the string contains a tag, the browser builds a real element in your page origin.
The safe path for a display name is textContent. After the write, a query for an image or bold element inside the slot returns null, which proves the tag was not created. The same characters remain visible, so the student can see exactly what was typed. Reach for createElement when you need structure, and put each untrusted string in textContent on its own node. That split is what keeps a comment preview from becoming an injection point.
Syntax & Parameters
node.textContent = text;
const text = node.textContent;
Example
Interactive preview available'use strict';
const untrusted = '<img src="x" alt="untrusted">';
function applyName(raw) {
const slot = document.getElementById('name-slot');
const proof = document.getElementById('parse-proof');
const source = document.getElementById('source-view');
const text = String(raw);
if (slot === null || proof === null) {
return { written: false, created: false, text };
}
slot.textContent = text;
const created = slot.querySelector('img, b');
if (source !== null) {
source.textContent = text;
}
proof.textContent = created === null
? 'No element created. The markup is visible text.'
: 'Element created.';
return { written: true, created: created !== null, text };
}
function readField() {
const field = document.getElementById('raw-name');
if (field instanceof HTMLInputElement) {
return field.value;
}
return untrusted;
}
const button = document.getElementById('apply-name');
if (button !== null) {
button.addEventListener('click', () => {
console.log(JSON.stringify(applyName(readField())));
});
}
console.log(JSON.stringify(applyName(untrusted)));
Expected Output
Console:
{"written":true,"created":false,"text":"<img src=\"x\" alt=\"untrusted\">"}
#name-slot and #source-view:
<img src="x" alt="untrusted">
#parse-proof:
No element created. The markup is visible text.
Line-by-Line Walkthrough
- untrusted is a normal string that looks like an image tag. It is data, and the sample never parses it as HTML.
- applyName reads the slot and the proof node and returns early when either one is missing, before any write.
- The raw value is forced through String so a number or other input still becomes text.
- slot.textContent stores that string. The browser shows the characters and does not create child elements from tags inside them.
- querySelector then looks for an img or b inside the slot. A null result means the tag was not parsed.
- The source view receives the same characters through textContent, so the page can show the exact input beside the rendered name.
- The proof line says that no element was created when the query returns null, and it says the opposite only if a child matched.
- readField uses the input when it is an HTMLInputElement, and otherwise falls back to the sample string.
- The button listens for click and runs applyName on whatever the field currently holds, then prints the report.
- On load, applyName runs with the sample string, so the slot, the proof, and the console all show the safe result immediately.
Common Pitfalls & Security
Assigning a user string with innerHTML parses it as HTML in the page origin. A comment name kept in untrustedName as the harmless string <img src="x" alt="untrusted"> and written with nameSlot.innerHTML = untrustedName becomes a real image element, not visible text. That parse is the XSS hole: the same assignment will build whatever markup the student typed, including event-handler attributes, and the browser will run it with the privileges of your course site. textContent writes the characters as text and does not create elements.
- Replacing children with innerHTML also drops event listeners that were on those descendants, so a refreshed comment list goes quiet.
- A sanitizer is a second defense for rich text you intentionally accept. It is not a reason to parse plain names.
- Concatenating strings into one HTML blob has the same hole when any piece is user input.
- textContent does not turn a tag such as a line-break tag into a line break. Use CSS or separate elements for layout.
- Reading innerHTML gives you a serialization, not the original typed string. Round-tripping a comment through it can change the text.
Best Practices & Modern Standards
Use textContent for every string a student, teacher, or API can influence: names, comments, scores, and error messages. Build structure with createElement, then set text on each node. ES2024 does not add a safe version of HTML parsing. The safe default is still to avoid parsing untrusted strings at all.
If a feature truly needs formatted text, keep the allowed tags on the server and send already structured fields, such as a separate title and body, instead of a blob of markup. In the browser, re-check after a textContent write by querying for unexpected elements when you are teaching or testing the path. The production widget should simply never parse the name.
Real-World Use
A comment form on a lesson page shows a live preview as the student types. The preview slot is updated with textContent on each input event, so a name or sentence that includes a tag appears literally. The proof line stays on "No element created," which is what you want before the comment is stored.
The saved comment is rendered the same way in the class discussion list. Authors, bodies, and timestamps are separate text nodes. A moderator dashboard can show the raw characters beside the preview and trust that both views are text, not a parsed fragment of HTML.
Frequently Asked Questions
When is textContent the right choice?
Use it whenever the value is text a person should read, especially text you did not write yourself. Names, comments, search queries, and scores belong in textContent. The characters show up as typed, including angle brackets.
Why is innerHTML called an XSS hole?
innerHTML parses the string as HTML and inserts the resulting nodes into your origin. A tag that was only meant to be visible can become a real element, and a hostile string can carry a handler. The page then runs that markup as if your site had written it.
Does textContent remove tags the user typed?
It does not strip them. It displays them as text, so the student still sees the characters. Nothing in the string becomes a child element. That is safer than deleting the characters or parsing them.
How do I build real elements without parsing a string?
Use createElement for each tag you intend, set textContent for the words, and append the nodes. The structure comes from your code and the words come from the data. A user string then cannot invent a new tag.