The DOM (Document Object Model) represents a web page as a tree of objects. JavaScript allows you to access, modify, and manipulate these objects dynamically. DOM manipulation is the key to creating interactive web pages.
This blog explains how to select and modify elements with examples.
⭐ 1. What Is DOM Manipulation?
DOM manipulation means changing the content, structure, or style of HTML elements using JavaScript. You can:
- Change text or HTML content
- Modify CSS styles
- Add or remove elements
- Respond to user events
⭐ 2. Selecting DOM Elements
1. By ID
let heading = document.getElementById("myHeading");
2. By Class
let items = document.getElementsByClassName("list-item");
3. By Tag Name
let paragraphs = document.getElementsByTagName("p");
4. Using Query Selector (Recommended)
let firstItem = document.querySelector(".list-item");
let allItems = document.querySelectorAll(".list-item");
⭐ 3. Modifying Content
Change Text
let heading = document.getElementById("myHeading");
heading.textContent = "New Heading";
Change HTML
let container = document.getElementById("container");
container.innerHTML = "<p>New Paragraph</p>";
⭐ 4. Modifying Styles
You can dynamically change CSS styles using the style property.
let box = document.getElementById("box");
box.style.backgroundColor = "yellow";
box.style.width = "200px";
box.style.border = "2px solid black";
⭐ 5. Adding & Removing Elements
Create Element
let newItem = document.createElement("li");
newItem.textContent = "New Item";
document.getElementById("list").appendChild(newItem);
Remove Element
let item = document.getElementById("item1");
item.remove();
⭐ 6. Handling Classes
let box = document.getElementById("box");
// Add class
box.classList.add("active");
// Remove class
box.classList.remove("active");
// Toggle class
box.classList.toggle("highlight");
// Check class
console.log(box.classList.contains("active")); // true or false
⭐ 7. Responding to Events
Combine DOM manipulation with events:
let button = document.getElementById("btn");
let box = document.getElementById("box");
button.addEventListener("click", function(){
box.style.backgroundColor = "blue";
});
⭐ Conclusion
DOM manipulation is essential for creating interactive and dynamic web pages. By learning to select, modify, add, or remove elements, you can control the structure and behavior of your website effectively.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/