Beginner level · Module 3: JavaScript for Web Pages · Lesson 2 of 3
Changing the Page with the DOM
Select elements, change their content and classes, and generate lists from data.
In this lesson you will
- Select elements and change their text and classes
- Generate page content from an array
Key concepts
querySelectortextContentclassListcreateElement and append
The lesson
document.querySelector finds the first element matching a CSS selector and querySelectorAll finds all of them. Change text with textContent and appearance by adding or removing classes with classList.
To display data, create elements with document.createElement, set their textContent and append them to a container. Clearing and rebuilding the container whenever the data changes keeps the page in step with the data.
Avoid building HTML strings with innerHTML from data that users or other systems provide; it can let attackers inject scripts. textContent is safe because it never interprets HTML.
Step by step
- Select the services container.
- Render the services list from the array.
- Highlight the selected category with a class.
- Re-render the list when the category changes.
Practice activity
Render the services list from data and highlight the active category.
Expected result: The list on the page always matches the data and the active category is visibly marked.
Check your understanding
-
Why is textContent safer than innerHTML for data?
Show answer
It never interprets HTML, so it cannot inject scripts.
-
How should the page change when data changes?
Show answer
Rebuild the affected content from the data.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.