DOM Manipulation
What is the DOM?
The DOM (Document Object Model) is a programming interface that represents an HTML page as a tree of objects. JavaScript can read and modify this tree to change what users see and interact with — without reloading the page.
When a browser loads an HTML file, it parses the markup and builds a DOM tree. Each HTML element becomes a node in that tree, and JavaScript can find, create, modify, or delete those nodes.
Selecting Elements
querySelector and querySelectorAll
document.querySelector returns the first element matching a CSS selector:
const heading = document.querySelector("h1");
const btn = document.querySelector(".primary-btn");
const input = document.querySelector("#email-input");
document.querySelectorAll returns all matching elements as a NodeList:
const allCards = document.querySelectorAll(".card");
allCards.forEach(card => {
console.log(card.textContent);
});
getElementById
A fast way to select a single element by its id:
const header = document.getElementById("site-header");
Changing Content and Attributes
const title = document.querySelector("h1");
// Change text content
title.textContent = "Welcome to CareerEx";
// Change HTML content (use with care — avoid user-supplied HTML)
title.innerHTML = "Welcome to <strong>CareerEx</strong>";
// Get and set attributes
const link = document.querySelector("a");
console.log(link.getAttribute("href")); // "/about"
link.setAttribute("href", "/courses");
Creating and Appending Elements
// Create a new element
const card = document.createElement("div");
card.textContent = "New Card";
card.className = "card";
// Append to the DOM
const container = document.querySelector(".container");
container.appendChild(card);
// Insert before an existing child
const firstChild = container.firstElementChild;
container.insertBefore(card, firstChild);
Changing Classes and Styles
The classList API lets you add, remove, and toggle CSS classes:
const button = document.querySelector(".btn");
button.classList.add("active");
button.classList.remove("disabled");
button.classList.toggle("highlighted"); // Add if missing, remove if present
console.log(button.classList.contains("active")); // true
You can also change inline styles directly (use CSS classes where possible for maintainability):
const box = document.querySelector(".box");
box.style.backgroundColor = "#42BCB1";
box.style.padding = "20px";
box.style.borderRadius = "8px";
Event Listeners
Event listeners let you respond to user actions. The most common is addEventListener:
const button = document.querySelector("#submit-btn");
button.addEventListener("click", function(event) {
console.log("Button clicked!");
console.log("Event type:", event.type);
});
Common Events
// Click
element.addEventListener("click", handler);
// Input — fires on every keystroke
input.addEventListener("input", (e) => {
console.log("Current value:", e.target.value);
});
// Form submit
form.addEventListener("submit", (e) => {
e.preventDefault(); // Prevent page reload
const data = new FormData(form);
console.log("Form submitted");
});
// Mouse events
element.addEventListener("mouseover", handler);
element.addEventListener("mouseout", handler);
// Keyboard events
document.addEventListener("keydown", (e) => {
console.log("Key pressed:", e.key);
});
Event Delegation
Instead of adding listeners to many elements, add one listener to a parent:
const list = document.querySelector(".lesson-list");
list.addEventListener("click", (e) => {
if (e.target.classList.contains("lesson-item")) {
console.log("Clicked:", e.target.textContent);
}
});
This is more efficient and works even for elements added later.
Key Takeaways
- The DOM (Document Object Model) represents the HTML page as a tree that JavaScript can read and modify
- Use document.querySelector for flexible CSS-style selection; document.getElementById for fast single-element selection
- textContent changes text safely; innerHTML parses HTML but should never be used with untrusted content
- classList.add/remove/toggle manages CSS classes without touching inline styles
- addEventListener attaches a function to run when a specific event occurs on an element
- e.preventDefault() stops the browser's default behaviour, such as a form refreshing the page on submit
Practice Exercise
- Select the counter
<p>element and the two buttons usingquerySelector - Store the count in a variable starting at 0
- Add a click listener to the increment button that increases the count and updates the paragraph text
- Add a click listener to the decrement button that decreases the count (stop at 0) and updates the text
- When count reaches 10, add the class
"complete"to the paragraph and change its colour using classList
Try it yourself
Key Takeaways
- The DOM (Document Object Model) is a tree of objects that JavaScript uses to read and modify an HTML page
- document.querySelector uses CSS selector syntax; document.querySelectorAll returns a NodeList of all matches
- textContent sets plain text safely; innerHTML parses HTML but should never be used with user input
- classList.add(), remove(), and toggle() are the clean way to apply CSS changes via JavaScript
- addEventListener(event, handler) responds to user actions; always use e.preventDefault() to stop default form submission
- Event delegation improves performance by attaching one listener to a parent rather than many listeners to children
Quick Quiz
1.What does document.querySelector('.card') return?
2.Why should you avoid using innerHTML with user-supplied content?
3.What does e.preventDefault() do in a form submit event listener?
4.What is event delegation and why is it useful?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx