Code Literacy

Unit 8 · Vibe coding with guardrails

innerHTML vs textContent: avoiding XSS

innerHTML treats its text as HTML and builds it, including anything that runs code. textContent shows text exactly as typed. Use textContent for anything that came from a user.

The mix-up

What people often think

“innerHTML is just a way to put text on the page.”

What the tutor says

innerHTML runs whatever HTML it is given. A visitor who types a script tag instead of a name gets their code running on your page.

What if someone typed <img src=x onerror=alert(1)> as their name?

How it works

If someone types <img src=x onerror=alert(1)> as their name and your page does greeting.innerHTML = "Hi " + name, their code runs on your page. That is cross-site scripting, and in real attacks the code steals data rather than showing an alert.

The fix is one word and loses nothing: the name still shows, just as plain text.

Side by side

The mix-upJavaScript
greeting.innerHTML = "Welcome, " + name;
A visitor’s HTML gets built and run.
What worksJavaScript
greeting.textContent = "Welcome, " + name;
Shown exactly as typed.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “Joining strings into innerHTML is harmless.”

    The name comes from a visitor. Glued into innerHTML, it becomes HTML that runs. Use textContent for anything a user typed.

  • “innerHTML is fine for showing what a visitor typed.”

    innerHTML turns the name into HTML that runs. textContent shows it as plain text, exactly as typed.

Practise it with a tutor watching

Break it: the AI's pull request

Review an AI-written pull request and fix a leaked key, an injection hole and a wrong edge case before it ships.

25 minutes See it Build it Break it Say it
Start the lesson

Free with an account. The first two units need no account.

© 2026 webfaCeMEdia. Code Literacy™ is a trademark of webfaCeMEdia.