DOM query methods allow JavaScript to locate HTML elements within the document tree. Modern web development relies heavily on querySelector and querySelectorAll using standard CSS selector syntax.
flowchart TD
Queries["DOM Query Methods"] --> Legacy["Legacy Methods: getElementById, getElementsByClassName"]
Queries --> Modern["Modern CSS Selectors: querySelector, querySelectorAll"]
Legacy --> L1["getElementById: Returns single Element by ID"]
Legacy --> L2["getElementsByClassName: Returns LIVE HTMLCollection"]
Modern --> M1["querySelector: Returns FIRST matching Element"]
Modern --> M2["querySelectorAll: Returns STATIC NodeList"]
| Method | Argument Format | Return Type | Collection Live/Static |
|---|---|---|---|
getElementById(id) |
String ID ("app") |
Element / null |
N/A (Single Element) |
getElementsByClassName(cls) |
String Class ("card") |
HTMLCollection |
Live |
getElementsByTagName(tag) |
String Tag ("div") |
HTMLCollection |
Live |
querySelector(selector) |
CSS Selector ("#app .card") |
Element / null |
N/A (First Match) |
querySelectorAll(selector) |
CSS Selector ("ul > li.active") |
NodeList |
Static |
// Demonstrating DOM querying methods and static vs live collections
document.addEventListener("DOMContentLoaded", () => {
// 1. Single Element Lookups
const appContainer = document.getElementById("app");
const mainHeading = document.querySelector("h1.title");
if (mainHeading) {
mainHeading.style.color = "#2563eb";
}
// 2. Multiple Element Lookups with querySelectorAll
const activeNavItems = document.querySelectorAll("nav.navbar a.active");
// NodeList supports native forEach iteration!
activeNavItems.forEach((link, index) => {
console.log(`Active Link #${index + 1}: ${link.textContent}`);
});
// 3. Converting NodeList to Array for Array operations
const allButtons = Array.from(document.querySelectorAll("button.btn"));
const primaryButtons = allButtons.filter(btn => btn.classList.contains("btn-primary"));
console.log(`Found ${primaryButtons.length} primary buttons.`);
});
querySelector / querySelectorAll: Modern CSS selector syntax allows complex querying (.card:first-child, [data-role="admin"]) matching standard CSS rules.querySelectorAll Returns a Static NodeList: Modifying the DOM after calling querySelectorAll will NOT update the previously returned NodeList.null: Always verify if (element !== null) before accessing properties on queried elements to prevent TypeError crashes.Write a querySelector call to select the first <input> element with attribute type="password".
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.