Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.3 — Changing Content
JavaScript · Example 3 of 3

User text must stay text (the XSS defence)

The stranger's text became real <img> and <u> elements in the unsafe list. These two are harmless, but the same door lets in elements whose attributes run code. With textContent the stranger's markup is only ever shown as characters.

textContent reads and writes plain text, innerText reads the text as it appears on screen, and innerHTML reads and writes HTML markup; use textContent for anything a user typed, because innerHTML turns text into real elements and opens the door to cross-site scripting (XSS).

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

A paragraph contains Price: <b>₹499</b>. Log its text without tags, then change only the number to ₹449 without using innerHTML.

02

Write a function showMessage(text) that puts any text into #message safely and returns the number of child elements #message has afterwards. Call it with "<em>hi</em>".

Explain it without notes

01

What are the differences between textContent, innerText and innerHTML?

02

What is XSS, and how does innerHTML make it possible?

03

Why is element.innerHTML += "..." a bad way to add content?

04

How would you safely display a comment that a user wrote, including their name in bold?

User text must stay text (the XSS defence)

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Elements created by the safe way: 0
Elements created by the unsafe way: 2
<img>