JavaScript DOM Manipulation
Learn how to interact with and manipulate the Document Object Model (DOM) using JavaScript.
Introduction to DOM Manipulation
The DOM represents the structure of a web page as a tree of objects. JavaScript can be used to dynamically change the content, structure, and style of a web page by manipulating the DOM.
Selecting Elements:
// Select element by ID
const header = document.getElementById("header");
// Select elements by class name
const items = document.getElementsByClassName("item");
// Select elements by tag name
const paragraphs = document.getElementsByTagName("p");
// Select using query selector
const firstItem = document.querySelector(".item");
// Select all matching elements
const allItems = document.querySelectorAll(".item");
Changing Text & HTML
let heading = document.getElementById("title");
heading.textContent = "New Title"; // plain text
heading.innerHTML = "<b>Bold Title</b>"; // renders HTML
Changing Styles
let box = document.querySelector(".box");
box.style.backgroundColor = "skyblue";
box.style.fontSize = "18px";
Creating & Appending Elements
let newPara = document.createElement("p");
newPara.textContent = "This is new!";
document.body.appendChild(newPara);
Removing Elements
let removeMe = document.getElementById("remove");
removeMe.remove();
Class Management
Use classList to work with CSS classes:
element.classList.add("highlight");
element.classList.remove("hidden");
element.classList.toggle("active");
Modifying Elements:
// Change text content
header.textContent = "New Header Text";
// Change HTML content
header.innerHTML = "New Header";
// Change styles
header.style.color = "blue";
// Add a class
header.classList.add("highlight");
// Remove a class
header.classList.remove("highlight");
Practice Task
Create a button that adds a paragraph dynamically when clicked:
<button onclick="addParagraph()">Add Text</button>
<script>
function addParagraph() {
let p = document.createElement("p");
p.textContent = "New content added!";
document.body.appendChild(p);
}
</script>