JavaScript โ Lesson 4
DOM Manipulation
Interacting with HTML elements using JavaScript.
DOM Manipulation
The DOM (Document Object Model) is JavaScript's way of interacting with HTML elements. You can read, change, add, or remove elements on the page.
Selecting Elements
// By ID
const header = document.getElementById("header");
// By class name (returns HTMLCollection)
const cards = document.getElementsByClassName("card");
// By tag name
const paragraphs = document.getElementsByTagName("p");
// Using CSS selectors (modern, recommended)
const firstBtn = document.querySelector(".btn");
const allBtns = document.querySelectorAll(".btn");
Changing Content
const title = document.querySelector("h1");
// Change text content
title.textContent = "New Title";
// Change HTML content
title.innerHTML = "New <em>Title</em>";
Changing Styles
const box = document.querySelector(".box");
box.style.backgroundColor = "red";
box.style.fontSize = "24px";
// Better: use classList
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("visible");
Creating and Removing Elements
// Create a new element
const newPara = document.createElement("p");
newPara.textContent = "I am new!";
// Add it to the page
document.body.appendChild(newPara);
// Remove an element
const oldEl = document.querySelector(".old");
oldEl.remove();
Event Listeners
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log("Button was clicked!");
button.textContent = "Clicked!";
});
Tip: Prefer
querySelector and querySelectorAll - they are versatile and use familiar CSS selector syntax.
Practice what you learned in the Deoit Editor โ a free, browser-based code editor.
Open Editor โ