Selecting Elements
Before you can change an element, you need to select it. querySelector and querySelectorAll are the modern methods — they accept any CSS selector. getElementById is faster for single elements.
Selection Methods
- querySelector(selector) — Returns FIRST matching element. Accepts any CSS selector
- querySelectorAll(selector) — Returns ALL matching elements as NodeList
- getElementById('id') — Fastest. Returns single element by ID
- getElementsByClassName('class') — Returns live HTMLCollection by class name
- getElementsByTagName('tag') — Returns live HTMLCollection by tag name
- querySelector is preferred — Most flexible: '#id', '.class', 'div > p', '[data-id]'
Selecting Elements Code
// querySelector — returns FIRST match
const heading = document.querySelector("h1");
const btn = document.querySelector("#submit-btn");
const card = document.querySelector(".card");
const nested = document.querySelector(".container > .card:first-child");
// querySelectorAll — returns ALL matches (NodeList)
const items = document.querySelectorAll(".item");
const links = document.querySelectorAll("nav a");
// Loop through NodeList
items.forEach((item, index) => {
console.log(`Item ${index}: ${item.textContent}`);
});
// getElementById — fastest for single element
const header = document.getElementById("header");
// Checking if element exists
const element = document.querySelector(".maybe-exists");
if (element) {
console.log("Found it!");
} else {
console.log("Not found");
}
// Selecting by data attributes
// <div data-user-id="123" data-role="admin">
const userEl = document.querySelector('[data-user-id="123"]');
const admins = document.querySelectorAll('[data-role="admin"]');Tip
Tip
Use querySelector/querySelectorAll for all DOM selection — they accept any CSS selector. getElementById is faster but limited. In modern code, querySelector is the standard because of its flexibility.
The DOM represents HTML as a tree of nodes that JavaScript can manipulate
Common Mistake
Warning
querySelectorAll returns a NodeList, not an array. Use Array.from(nodeList) or [...nodeList] to access array methods like map and filter. forEach works on NodeList but map/filter don't.
Practice Task
Note
Practice selectors: (1) Select an element by ID, class, and tag. (2) Select all list items with querySelectorAll and log their text. (3) Select a nested element using a complex CSS selector like '.container > .card:first-child'.
Quick Quiz
Key Takeaways
- Before you can change an element, you need to select it.
- querySelector(selector) — Returns FIRST matching element. Accepts any CSS selector
- querySelectorAll(selector) — Returns ALL matching elements as NodeList
- getElementById('id') — Fastest. Returns single element by ID