Changing the Page Safely
Worked example: render a message feed from data, update cards in place and remove them — inserting every piece of user text as text, never as markup.
Contentsand lesson path
On this page
- The problem
- Step 1: watch innerHTML get it wrong
- Step 2: render each message as a card
- Step 3: update a card in place
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of DOM Manipulation & Events
- The DOM as a Live Tree Concept · 15 min
- Changing the Page Safely Worked example · 20 min
- Listeners, Propagation and Default Actions Concept · 25 min
- Lab: A Filterable List Driven by One Delegated Listener Lab · 30 min
- Keeping UI and Data in Sync, and Remembering It Concept · 15 min
- Check: Find and Fix the Interaction Bugs Knowledge check · 6 questions
What you will learn
- Select, create, update and remove DOM nodes, inserting user-supplied text safely with textContent instead of innerHTML.
Prerequisites: JavaScript Foundations
01. The problem
A discussion page keeps its messages in a JavaScript array. Your job is to turn that array into cards on the page — and to keep the page in step as messages are flagged, edited and deleted. Every message body is user-supplied text, which means some of it will look like HTML: a pasted snippet, a stray angle bracket, or something crafted to break the page.
This is the classic first scripting task, and it has one rule that matters more than any other: user text goes into the page as text, not as markup. The browser has an API for exactly this — textContent — and a tempting shortcut that gets it wrong: innerHTML. We will see why the shortcut is wrong by watching it fail, then build the safe version properly.
The data shape drives the page shape: one entry in the array becomes one card on the screen. That correspondence is worth keeping deliberate, because every change later in this lesson — flagging a card, editing its text, deleting it — is really a change to the data that has to be echoed onto the matching card. When the two drift apart, users see ghosts: messages that are gone from the array but still on the screen.
02. Step 1: watch innerHTML get it wrong
Suppose we insert a message with innerHTML — the property that hands a string to the HTML parser. Here is the same hostile string placed into two empty containers, one by each API:
const unsafe = document.querySelector("#unsafe");
const safe = document.querySelector("#safe");
const hostile =
'<b>hi</b><img src=x onerror="window.pwned = true">';
unsafe.innerHTML = hostile; // parsed as HTML: a real img appears
safe.textContent = hostile; // plain text, exactly as typed
console.log('img in unsafe:', unsafe.querySelectorAll('img').length);
console.log('img in safe:', safe.querySelectorAll('img').length);
console.log('safe text:', safe.textContent);
// Image loading is asynchronous, so check the handler a moment later.
setTimeout(() => {
console.log('onerror ran after innerHTML:', window.pwned ?? false);
}, 100);img in unsafe: 1
img in safe: 0
safe text: <b>hi</b><img src=x onerror="window.pwned = true">
onerror ran after innerHTML: trueRead the last line carefully: onerror ran after innerHTML: true. Assigning that string to innerHTML created a real <img> element; the browser then tried to load it, failed, and ran the code in the onerror attribute. An attacker who controls the string controls code that runs in your page — this is cross-site scripting, usually shortened to XSS. MITRE’s 2025 CWE Top 25, which ranks weaknesses by how often and how severely they appear in published vulnerability records, puts it in first place. (<script> elements inserted this way do not execute, but event-handler attributes like onerror do — the quiz for this skill digs into that distinction.)
With textContent, nothing was parsed: the angle brackets are characters on the screen, not markup. The browser escapes them when it serialises the page, so nothing can run.
03. Step 2: render each message as a card
The safe pattern for structured content is to build the elements yourself and set only the variable parts with textContent. A small function per card keeps this readable:
function renderMessage(message) {
const card = document.createElement('article');
card.className = 'message';
const author = document.createElement('h3');
author.textContent = message.author;
const body = document.createElement('p');
body.textContent = message.text;
card.append(author, body);
return card;
}
const messages = [
{ author: 'Ada', text: 'Ship it on Friday.' },
{ author: 'Sam', text: '<img src=x onerror="alert(1)">' },
];
const feed = document.querySelector('#feed');
for (const message of messages) feed.append(renderMessage(message));
console.log('cards:', feed.children.length);
console.log('img elements:', feed.querySelectorAll('img').length);
console.log(
'second body:',
feed.children[1].querySelector('p').textContent,
);cards: 2
img elements: 0
second body: <img src=x onerror="alert(1)">Sam’s hostile message renders as visible text — ugly, but harmless, and exactly what the user typed. document.createElement takes the bare tag name (passing "<article>" throws), append accepts several nodes at once, and because every node was created rather than parsed, no markup can smuggle itself in.
One small trap sits nearby: append also accepts plain strings, and a string argument becomes a text node — safe. The dangerous lookalike is any method whose name ends in HTML, because those parse. If you keep the two families apart — node-building methods versus HTML-parsing properties — you can tell at a glance whether a line is safe for user input.
04. Step 3: update a card in place
Messages get edited. The wrong instinct is to rebuild everything; often you can just touch the node you have. Here we flag the first card: add a class (which its CSS can style), stamp a data-* attribute, and replace the body text:
const first = feed.children[0];
first.classList.add('flagged');
first.dataset.status = 'flagged';
first.querySelector('p').textContent = 'Ship it on Monday.';
console.log('class:', first.className);
console.log('status:', first.dataset.status);
console.log('body now:', first.querySelector('p').textContent);
feed.querySelector(".message").remove();
console.log('after remove:', feed.children.length);class: message flagged
status: flagged
body now: Ship it on Monday.
after remove: 1classList.add never clobbers existing classes, unlike className = ..., which replaces the whole attribute. dataset.status writes the data-status attribute. remove() detaches the node from the tree at once — no refresh, no reload.
How do you choose between touching one node and rebuilding the list? Touching a node is cheap and precise, but every place that does it is another place that can forget a step — forget to re-apply a filter, forget to update a counter. Rebuilding from data is blunter but has a single code path. For a feed of a few dozen messages either works; the drift risk decides. This skill returns to that trade-off in the lab and again in the lesson on keeping UI and data in sync.
05. Common mistakes
The three verbs of this lesson have safe forms worth memorising. Create: createElement plus textContent, connected with append. Update: classList.add or toggle for classes, dataset for data-* attributes, textContent for text. Remove: element.remove(). If a line of your code contains both innerHTML and something that came from the user, stop and rewrite it with this toolkit — that one habit removes the most dangerous bug class a beginner can ship.
06. Check your understanding
07. Apply it
Sketch the first slice of the shopping-list practice with today’s pattern, no events yet: define an array of two or three items in the script, write a renderItem(item) function that builds an li with the item text in a span and a real button labelled Remove, append them on load, and log the list’s children.length. Then try to break it: put <b> inside one item’s text and confirm it shows up as characters.
08. Review prompt
Without looking back: why does assigning user text to innerHTML let an attacker run code in your page, and why does textContent not? Name three ways to get HTML parsed from a string. When you need to change one card in a rendered list, which three properties from this lesson do you reach for, and what does each one do?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.