JavaScript Lesson 10: DOM Manipulation
The DOM (Document Object Model) is how JavaScript sees and controls an HTML page. This is where JavaScript gets really exciting — you can change anything on a webpage dynamically.
Selecting Elements
// By ID (returns one element)
const title = document.getElementById("main-title");
// By CSS selector (returns first match)
const btn = document.querySelector(".submit-btn");
const input = document.querySelector("#email");
// By CSS selector (returns ALL matches)
const items = document.querySelectorAll(".menu-item");
const paragraphs = document.querySelectorAll("p");
console.log(items.length); // number of matches
Changing Content and Style
const title = document.querySelector("h1");
// Change text
title.textContent = "New Title";
title.innerHTML = "Title with <em>emphasis</em>";
// Change CSS
title.style.color = "#6366f1";
title.style.fontSize = "32px";
title.style.display = "none"; // hide
title.style.display = "block"; // show
// Add/remove CSS classes (best practice)
title.classList.add("highlighted");
title.classList.remove("hidden");
title.classList.toggle("active");
title.classList.contains("active"); // true/false
Creating and Inserting Elements
// Create a new element
const newItem = document.createElement("li");
newItem.textContent = "New item";
newItem.classList.add("list-item");
// Insert into the page
const list = document.querySelector("ul");
list.appendChild(newItem); // at the end
list.prepend(newItem); // at the start
list.insertAdjacentHTML("beforeend", "<li>HTML item</li>");
Reading and Setting Attributes
const img = document.querySelector("img");
// Read attribute
console.log(img.getAttribute("src"));
console.log(img.src); // direct property
// Set attribute
img.setAttribute("alt", "A sunset photo");
img.src = "new-image.jpg";
// Input values
const input = document.querySelector("input");
console.log(input.value); // what user typed
input.value = "preset text";
🏋️ Practice Task
Create an HTML file with: a heading, a paragraph, a button, and an empty div. When the button is clicked, change the heading text, change the paragraph color to purple, and add a new item to the div. Use querySelector and style manipulation.
💡 Hint: Add a script tag at the bottom. Use querySelector to get elements. Change .textContent and .style.color.