10. DOM Manipulation Basics
What Is the DOM?
The Document Object Model (DOM) is a structured representation of your web page. JavaScript can use it to read and modify HTML elements dynamically — meaning your site can respond to user actions in real time.
<h1 id="title">Hello World</h1>
<button id="btn">Click Me</button>The DOM treats every element like a JavaScript object you can access and manipulate.
Selecting Elements
To change an element, you first need to select it. The most common methods are `getElementById`, `querySelector`, and `querySelectorAll`.
const title = document.getElementById("title");
const button = document.querySelector("#btn");Changing Content and Style
You can easily change an element’s text, HTML, or style properties.
title.textContent = "Welcome to JavaScript!";
title.style.color = "lime";
title.style.fontSize = "2rem";Handling Events
Events let your page respond to user actions like clicks, hovers, and keypresses.
button.addEventListener("click", () => {
title.textContent = "You clicked the button!";
title.style.color = "pink";
});Creating and Appending Elements
You can create new elements and insert them into the DOM using `createElement()` and `appendChild()`.
const newPara = document.createElement("p");
newPara.textContent = "This paragraph was added with JavaScript!";
document.body.appendChild(newPara);Removing Elements
You can remove existing elements with `.remove()`.
title.remove(); // Removes the <h1> elementMini Challenge
Create a button that, when clicked, adds a new `<li>` item to a `<ul>` list. Bonus: make each new item have a random background color!
<ul id="list"></ul>
<button id="add">Add Item</button>const list = document.getElementById("list");
const button = document.getElementById("add");
button.addEventListener("click", () => {
const newItem = document.createElement("li");
newItem.textContent = `Item ${list.children.length + 1}`;
newItem.style.background = `hsl(${Math.random() * 360}, 70%, 60%)`;
list.appendChild(newItem);
});Key Takeaway
DOM manipulation is what makes web pages dynamic and interactive. By selecting elements, listening for events, and updating the DOM, you bring your pages to life.