getElementById
The fastest way to select a single element by its id attribute. Returns one element or null.
const title = document.getElementById("main-title");
if (title) {
title.style.color = "red";
console.log(title.textContent);
}
Try it Yourself โ
querySelector
Returns the first element matching any CSS selector. Powerful and flexible.
const firstBtn = document.querySelector(".btn");
const header = document.querySelector("header h1");
const nav = document.querySelector("#nav > ul");
if (firstBtn) firstBtn.textContent = "Clicked!";
if (header) console.log(header.textContent);
Try it Yourself โ
querySelectorAll
Returns a static NodeList of all elements matching a CSS selector. Iterate with forEach or a for...of loop.
const items = document.querySelectorAll(".list-item");
console.log("Found " + items.length + " items");
items.forEach((item, index) => {
item.textContent = "Item " + (index + 1);
});
const paragraphs = document.querySelectorAll("p.highlight");
for (let p of paragraphs) {
p.style.fontWeight = "bold";
}
Try it Yourself โ