LESSON 25

Changing Content

Learning objective: Update text and HTML on the page with JavaScript.

Understand

Once selected, an element's content can be changed.

Use .textContent to change plain text safely and .innerHTML to set HTML markup. Prefer textContent for user-provided text to avoid injecting unwanted HTML.

Analogy: Changing content is like rewriting the label on a jar while it sits on the shelf.

See It in Action

Updating a heading's text:

const title = document.querySelector("#title");
title.textContent = "Updated!";
How it works: Selecting the element then setting .textContent instantly changes the visible text on the page.

Try It Yourself

  1. Select an element and change its textContent.
  2. Try setting innerHTML with a tag.
  3. Refresh and confirm the change.

Quick Quiz

Which is safer for inserting plain user text?

Challenge

Change a paragraph's text when the page loads.

Success condition: The paragraph shows your new text on load.