Command Palette

Search for a command to run...

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

Setting text versus setting HTML

The first span shows the angle brackets as characters: the browser escaped them (&lt; is how < is written as text in HTML). The second span parsed the string and created a real <b> element.

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?

Setting text versus setting HTML

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

&lt;b&gt;Hi&lt;/b&gt; &amp; welcome
0 1
<b>