← All topics

LESSON 08 OF 10

Changing the Page

Select HTML elements and change their content.

Before this lesson: complete the preceding lessons or review their examples. No installation or account is needed.

The idea

The Document Object Model (DOM) represents a page as objects. document.querySelector finds the first matching element, or returns null if none matches. Use textContent when you want to display plain text.

At a glance

SyntaxPurpose
document.querySelector()Find the first element matching a CSS selector
.textContentRead or replace plain text
document.createElement()Create a new DOM element

Try it yourself

The preview starts with <p id="message">Waiting for JavaScript.</p>. Change the selector or the new text.

Ready. Run the example to open its preview.

Console output

Not run yet.

Page preview

Expected result
Page updated

What to watch for

A selector beginning with # refers to an id; one beginning with . refers to a class. Query after the element exists, such as with an external defer script. Avoid inserting untrusted text with innerHTML; textContent treats it as text.

Your turn

Create a paragraph, set its text to One small step, and append it to the preview’s body.

Show one solution
const paragraph = document.createElement("p");
paragraph.textContent = "One small step";
document.body.append(paragraph);

Check your understanding

Why might querySelector return null?

The selector may not match any element, or the code may run before that element is parsed.

Read alongside this lesson

W3Schools: Changing the Page · All learning sources