DOM manipulation
You use the Document Object Model (DOM) to manipulate HTML elements. The DOM is a tree-structured representation of HTML that lets you touch it from JavaScript.
Getting elements
// Get an element by ID
const header = document.getElementById("header");
// Get an element by CSS selector (the first match)
const container = document.querySelector(".container");
// Get elements by CSS selector (all matches)
const buttons = document.querySelectorAll("button");
// Get by class name or tag name
const items = document.getElementsByClassName("item");
const paragraphs = document.getElementsByTagName("p");
getElementsByClassName / getElementsByTagName return a live HTMLCollection that tracks changes in the DOM. querySelectorAll, on the other hand, returns a static NodeList frozen at the state when it was retrieved. When you add or remove elements during a loop, this difference can lead to differences in behavior. When in doubt, using querySelector / querySelectorAll is the safer choice.
Manipulating elements
const header = document.getElementById("header");
const container = document.querySelector(".container");
// Changing the text content
header.textContent = "New header";
// Changing the HTML content
container.innerHTML = "<p>New content</p>";
// Manipulating attributes
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
console.log(link.getAttribute("href")); // https://example.com
// Changing styles
header.style.color = "blue";
header.style.fontSize = "24px";
// Adding, removing, and toggling classes
container.classList.add("highlight");
container.classList.remove("hidden");
container.classList.toggle("active"); // Remove the class if present, add it if not
console.log(container.classList.contains("highlight")); // true
If you put a string entered by a user directly into innerHTML, there's a risk of XSS (cross-site scripting), where a malicious script runs. If you only need to display text, use textContent. Use innerHTML only for trusted content that you prepared yourself.
Creating and adding elements
const container = document.querySelector(".container");
// Creating a new element
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
// Adding an element (at the end)
container.appendChild(newParagraph);
// Inserting an element at a specific position (at the beginning)
container.insertBefore(newParagraph, container.firstChild);
// Removing an element
newParagraph.remove(); // Widely supported in modern browsers
DOM manipulation is the basis for changing a web page dynamically. However, building a complex UI with raw DOM manipulation alone becomes hard to manage. Once things get large, using a framework such as React or Vue is more efficient.
What to read next
- Event handling — React to user actions like clicks to drive the DOM