Lesson 43 - Modifying Elements in the DOM
This lesson focuses on modifying HTML elements using JavaScript. You will learn how to change text content, update attributes, and modify styles dynamically.
1. Changing Text Content
Use .textContent
or .innerHTML
to change the content of an element.
Example 1: Changing Text with textContent
document.getElementById("message").textContent = "Hello, JavaScript!";
- Updates the text inside the element without interpreting HTML.
Example 2: Changing Text with innerHTML
document.getElementById("message").innerHTML = "<strong>Bold Text</strong>";
- Parses HTML, so
<strong>
is rendered as bold.
2. Changing Element Attributes
Modify attributes like src
, href
, alt
, etc., using .setAttribute()
or direct property manipulation.
Example 1: Updating Image Source
document.getElementById("myImage").src = "new-image.jpg";
Example 2: Updating Link URL
document.getElementById("myLink").href = "https://lancecourse.com";
3. Changing CSS Styles
Use .style.property
or .classList
to modify styles dynamically.
Example 1: Changing Color with .style
document.getElementById("title").style.color = "blue";
Example 2: Adding and Removing CSS Classes
document.getElementById("box").classList.add("highlight"); // Add a class
document.getElementById("box").classList.remove("hidden"); // Remove a class
Try Your Hand
Steps:
- Create a File: Name it
lesson43-modifying-elements.html
-
Write the Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 43 - Modifying Elements</title> <style> .highlight { color: red; font-weight: bold; } </style> </head> <body> <h2 id="title">Modify This Text</h2> <button onclick="changeText()">Change Text</button> <button onclick="changeColor()">Change Color</button> <script> function changeText() { document.getElementById("title").textContent = "Text Changed!"; } function changeColor() { document.getElementById("title").classList.toggle("highlight"); } </script> </body> </html>
- Save and Open in a Browser to see dynamic text and style updates.
Key Takeaways
.textContent
modifies text without parsing HTML..innerHTML
modifies text and parses HTML..setAttribute()
changes element attributes..style.property
modifies styles dynamically..classList
helps add, remove, or toggle classes.