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
greeting.innerHTML = "Welcome, " + name;greeting.textContent = "Welcome, " + name;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.
Free, no account needed.