The DOM (Document Object Model) allows JavaScript to interact with web pages.
It represents the structure of an HTML document as a tree that JavaScript can read and modify.
Selecting Elements
JavaScript provides several methods to select HTML elements.
querySelector
const title = document.querySelector("h1");querySelectorAll
const items = document.querySelectorAll(".item");getElementById
const box = document.getElementById("container");Changing Text Content
const heading = document.querySelector("h1");
heading.textContent = "New Title";Changing Inner HTML
heading.innerHTML = "<span>Hello</span>";Modifying Styles
heading.style.color = "red";
heading.style.fontSize = "24px";Working With Classes
heading.classList.add("active");
heading.classList.remove("hidden");
heading.classList.toggle("dark");Creating and Adding Elements
const newItem = document.createElement("li");
newItem.textContent = "New list item";
const list = document.querySelector("ul");
list.appendChild(newItem);Removing Elements
newItem.remove();Handling Attributes
const img = document.querySelector("img");
img.setAttribute("alt", "A beautiful photo");
img.getAttribute("src");
img.removeAttribute("title");DOM Tree Navigation
element.parentNode
element.children
element.firstChild
element.lastChild Useful for exploring or modifying structure.
Summary
In this lesson, you learned:
- How the DOM works
- How to select elements
- How to update text, HTML, styles
- How to work with classes and attributes
- How to create, insert, and remove elements
- How to navigate the DOM tree
In the next lesson, we will explore Events and Event Listeners — making your pages interactive.