60 Mins intermediate
10. DOM Manipulation
Browser API
DOM Manipulation
The Document Object Model (DOM) is an object-oriented representation of the web page. This is how JavaScript physically reaches into the HTML and changes it on the fly.
🔍 Selecting Elements
Before you can change an HTML element, you have to grab it. document.querySelector is the modern, most powerful way to select elements using standard CSS selectors.
// Grabs the first
on the page const heading = document.querySelector("h1"); // Grabs the element with the class "submit-btn" const button = document.querySelector(".submit-btn"); // Grabs ALL elements with the class "card" (returns a list) const cards = document.querySelectorAll(".card");
✏️ Updating HTML and CSS
Once selected, you have total control over the element's text, HTML structure, and inline CSS styles.
const statusBox = document.querySelector("#status");
// Change the text
statusBox.textContent = "Upload Complete!";
// Inject raw HTML
statusBox.innerHTML = "Success: Upload Complete!";
// Modify CSS styles instantly
statusBox.style.backgroundColor = "green";
statusBox.style.color = "white";
✨ Adding and Removing Classes
Modifying inline CSS via JavaScript is messy. Best practice is to define CSS classes in your stylesheet, and use JavaScript to add or remove those classes.
const modal = document.querySelector(".modal");
// Adds the 'hidden' class to make it disappear
modal.classList.add("hidden");
// Removes it to show it again
modal.classList.remove("hidden");
// Toggles it (if it's there, remove it; if not, add it)
modal.classList.toggle("dark-mode");
Note: DOM manipulation requires a browser environment. Because our Interactive Sandbox is isolated for pure logic execution, DOM methods like
document.querySelector cannot be executed in the editor panel.Knowledge Check
Ready to test your understanding of 10. DOM Manipulation?