The DOM (Document Object Model) is a programming interface for web documents. It represents an HTML or XML document as a tree structure, where each element is a node.
JavaScript can interact with the DOM to:
✔ Change HTML content
✔ Modify CSS styles
✔ Add or remove elements
✔ Handle event.
When a web page loads, the browser creates a DOM tree of the page. JavaScript can access this tree and modify elements dynamically.
JavaScript provides several methods to select elements:
getElementById
Selects an element by its ID.
let heading = document.getElementById("title");
heading.innerHTML = "New Title";
getElementsByClassName
Selects multiple elements by their class name.
let items = document.getElementsByClassName("item");
items[0].style.color = "red";
getElementsByTagName
Selects multiple elements by their tag name.
let paragraphs = document.getElementsByTagName("p");
paragraphs[0].innerText = "Updated paragraph!";
querySelector
Selects the first matching element using CSS selectors.
let firstDiv = document.querySelector("div");
firstDiv.style.backgroundColor = "yellow";
querySelectorAll
Selects all matching elements using CSS selectors.
let allItems = document.querySelectorAll(".item");
allItems.forEach(item => item.style.fontWeight = "bold");
Once selected, you can change the content, style, and attributes of elements.
document.getElementById("title").innerHTML = "Hello, DOM!";
document.getElementById("title").textContent = "New Text";