Command Palette

Search for a command to run...

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

textContent, innerText and innerHTML side by side

textContent includes the hidden span; innerText follows the CSS and leaves it out. innerHTML shows the markup; outerHTML adds the <p> itself.

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?

textContent, innerText and innerHTML side by side

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Hello there (secret)
Hello there
Hello <b>there</b><span class="hidden"> (secret)</span>
true