JavaScript DOM Manipulation: A Beginner’s Guide
The Document Object Model (DOM) is a representation of the HTML structure of a webpage. JavaScript can interact with the DOM to read, modify, or add content, allowing your webpages to be dynamic and interactive.
Understanding DOM manipulation is crucial for building modern web apps.
1. Accessing DOM Elements
Before you can manipulate an element, you need to select it.
getElementById
Selects a single element by its ID:
const title = document.getElementById("main-title");
console.log(title.textContent);getElementsByClassName
Selects elements with a specific class (returns a live HTMLCollection):
const items = document.getElementsByClassName("item");
console.log(items[0].textContent);querySelector and querySelectorAll
Modern and flexible, supports CSS selectors:
const firstItem = document.querySelector(".item"); // first matching
const allItems = document.querySelectorAll(".item"); // NodeList of allUse
querySelectorfor a single element andquerySelectorAllfor multiple elements.
2. Changing Content and Attributes
textContent and innerHTML
const message = document.getElementById("message");
message.textContent = "Hello, world!"; // sets plain text
message.innerHTML = "<strong>Hello!</strong>"; // can add HTMLsetAttribute and getAttribute
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
console.log(link.getAttribute("href"));
3. Changing Styles
You can modify inline styles via the style property:
const box = document.querySelector(".box");
box.style.backgroundColor = "lightblue";
box.style.border = "2px solid black";For adding/removing multiple classes, classList is very handy:
box.classList.add("highlight");
box.classList.remove("hidden");
box.classList.toggle("active"); // add if missing, remove if present
4. Creating and Removing Elements
Creating Elements
const newItem = document.createElement("li");
newItem.textContent = "New List Item";
document.querySelector("#my-list").appendChild(newItem);Removing Elements
const lastItem = document.querySelector("#my-list li:last-child");
lastItem.remove();
5. Handling Events
DOM manipulation is often paired with event handling.
const button = document.querySelector("#my-button");
button.addEventListener("click", () => {
alert("Button clicked!");
});Other common events:
mouseover,mouseoutkeydown,keyupsubmit(forms)input(text fields)
6. Practical Example: To-Do List
Here’s a simple example of adding items to a list dynamically:
<input type="text" id="task-input" placeholder="Add task" />
<button id="add-btn">Add</button>
<ul id="tasks"></ul>
<script>
const input = document.getElementById("task-input");
const button = document.getElementById("add-btn");
const tasks = document.getElementById("tasks");
button.addEventListener("click", () => {
if (input.value.trim() === "") return;
const li = document.createElement("li");
li.textContent = input.value;
tasks.appendChild(li);
input.value = "";
});
</script>Now, every time the button is clicked, a new <li> is added to the list dynamically—classic DOM manipulation in action!
Key Takeaways
- Select elements with
getElementById,querySelector, orquerySelectorAll. - Change content with
textContentorinnerHTML. - Manipulate attributes and classes with
setAttributeandclassList. - Create and remove elements with
createElementandremove. - Respond to user interactions with
addEventListener.