Week 3
3.6 DOM Manipulation
Week 3
3.6 DOM Manipulation
DOM Manipulation – Bringing Webpages to Life!
JavaScript allows us to interact with web pages dynamically through the Document Object Model (DOM). DOM Manipulation is one of the most powerful features of JavaScript, enabling us to change content, styles, and even respond to user actions!
1. What is the DOM?
The Document Object Model (DOM) is a representation of an HTML document as a tree of objects. JavaScript can access and modify this tree to change the webpage dynamically.
When a browser loads an HTML page:
1️⃣ It reads the HTML and creates a DOM tree.
2️⃣ JavaScript can use this tree to modify elements, change styles, and add interactivity.
Think of the DOM as a bridge between JavaScript and HTML!
Example HTML Page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id="title">Hello, DOM!</h1>
<p class="message">JavaScript can change me!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("title").innerText = "DOM Changed!";
}
</script>
</body>
</html>
Clicking the button changes the h1 text dynamically!
2. Selecting Elements – Finding Elements in the DOM
Before modifying an element, we must select it. JavaScript provides multiple ways to grab elements from the DOM.
const heading = document.getElementById("title");
console.log(heading.innerText); // Output: Hello, DOM!
Use when selecting a single, unique element by its ID.
const firstParagraph = document.querySelector(".message");
console.log(firstParagraph.innerText);
Selects the first element that matches a CSS selector (.class, #id, tag).
const allParagraphs = document.querySelectorAll("p");
console.log(allParagraphs.length); // Output: Number of `<p>` elements
Returns a NodeList (like an array), allowing us to loop through multiple elements!
3. Modifying Elements – Changing Content & Style
Once an element is selected, we can change its content and appearance dynamically!
const heading = document.getElementById("title");
heading.innerText = "New Heading!"; // Changes only the text
heading.innerHTML = "<em>New Heading!</em>"; // Can include HTML tags
Use innerText for plain text and innerHTML when working with HTML.
We can change CSS styles dynamically using JavaScript.
const heading = document.getElementById("title");
heading.style.color = "red";
heading.style.fontSize = "24px";
Good for quick style changes, but avoid using it excessively (use classList instead).
Instead of changing styles manually, we can toggle CSS classes dynamically.
const heading = document.getElementById("title");
heading.classList.add("highlight"); // Adds a class
heading.classList.remove("highlight"); // Removes a class
heading.classList.toggle("highlight"); // Toggles class on/off
Using classList is more efficient than modifying style.
4. Adding & Removing Elements – Dynamic Content
We can create, add, and remove elements dynamically in JavaScript!
const newParagraph = document.createElement("p");
newParagraph.innerText = "This is a new paragraph!";
document.body.appendChild(newParagraph);
createElement() creates a new element, and appendChild() adds it to the page.
const removeMe = document.getElementById("title");
removeMe.parentNode.removeChild(removeMe);
Always remove an element from its parent node!
5. Event Listeners – Making Pages Interactive
An event is something that happens on a webpage, like clicking a button, typing in an input, or hovering over an element.
We use addEventListener() to respond to these events.
const button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Button clicked!");
});
This ensures the event runs only when the button is clicked!
const heading = document.getElementById("title");
const button = document.querySelector("button");
button.addEventListener("click", function() {
heading.innerText = "Text Changed!";
});
Clicking the button changes the heading dynamically!
const box = document.getElementById("box");
box.addEventListener("mouseover", function() {
box.style.backgroundColor = "yellow";
});
box.addEventListener("mouseout", function() {
box.style.backgroundColor = "white";
});
This changes the color when you hover over the element.
6. Event Object (event) – Getting More Info
When an event occurs, JavaScript provides details through an event object (event).
Example: Logging mouse click coordinates
document.addEventListener("click", function(event) {
console.log("X:", event.clientX, "Y:", event.clientY);
});
The event object contains data about the event, like mouse position or key pressed.
Final Recap – What We Learned!
DOM (Document Object Model) allows JavaScript to modify webpages dynamically.
Selecting elements: getElementById(), querySelector(), querySelectorAll()
Modifying elements: innerText, innerHTML, style, classList
Adding/removing elements: appendChild(), removeChild()
Event listeners make webpages interactive with addEventListener()
Quick Challenge – What’s the Output?
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Test</title>
</head>
<body>
<h1 id="text">Click me!</h1>
<script>
const heading = document.getElementById("text");
heading.addEventListener("click", function() {
heading.innerText = "You clicked me!";
heading.style.color = "blue";
});
</script>
</body>
</html>
What happens when you click the heading?
Next Up: JavaScript ES6+ Features!