In this lesson, you will learn how to update text, classes, and attributes on web pages using the Document Object Model (DOM). This is an essential skill for making your web pages interactive and visually appealing.
Updating elements on a webpage is similar to changing a name tag. For example, when you rename a friend in your phone, you’re updating their information. In a webpage, you can change text, styles, and attributes in the same way. Updating text, classes, and attributes allows you to customize how the content appears and behaves.
File: update-elements.js
// Select elements and update their properties
const title = document.querySelector('.title');
title.textContent = 'Welcome to My Web Page!';
title.classList.add('highlight');
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
link.textContent = 'Visit Example';
Output:
The text "Welcome to My Web Page!" is displayed.
The link now points to example.com and displays "Visit Example".
In the code, document.querySelector('.title') selects the element with the class title. The line title.textContent = 'Welcome to My Web Page!'; changes the text displayed on the page. Additionally, adding highlight to the class list with classList.add changes its visual style. Finally, setAttribute modifies the link’s destination, allowing for dynamic interactions.
Now it’s your turn! Create an HTML page with a title, a paragraph, and a link. Use JavaScript to change the title text, adjust the paragraph’s class, and update the link. Ensure the new link leads to a relevant site. If you need guidance, refer to the lesson on connecting a JavaScript file.
// HTML structure
// <h1 class="title">Old Title</h1>
// <p class="description">This is a description.</p>
// <a href="#">Old Link</a>
const title = document.querySelector('.title');
title.textContent = 'New Amazing Title';
description.classList.add('new-class');
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
link.textContent = 'New Link';
querySelector correctly: Always double-check the selector you are using to ensure it matches the desired element.classList.add works to avoid making style alterations that do not appear.textContent effectively.