Topic 76 of 87
Selecting Elements
Overview
Before you can change an HTML element, you must "grab" or select it from the DOM tree.
Historically, developers used methods like getElementById or getElementsByClassName. Today, modern JavaScript almost exclusively uses querySelector and querySelectorAll because they allow you to select elements using standard CSS selectors (like .class, #id, or div > p).
Syntax
Modern Selection (querySelector)
javascript
// Selects the FIRST matching element (returns a single Node)
const header = document.querySelector('header');
const btn = document.querySelector('.submit-btn');
const input = document.querySelector('#email-input');
// Selects ALL matching elements (returns a NodeList)
const allButtons = document.querySelectorAll('.btn');
// NodeLists can be iterated over!
allButtons.forEach(button => {
console.log(button);
});Legacy Selection (Still widely used)
javascript
// By ID (Extremely fast)
const app = document.getElementById('root');
// By Class Name (Returns an HTMLCollection, NOT a NodeList)
// WARNING: HTMLCollections cannot use .forEach()!
const items = document.getElementsByClassName('list-item');Common Pitfalls
- Confusing a
NodeListwith a true Array.querySelectorAllreturns a NodeList. While modern browsers allow.forEach()on NodeLists, you cannot use.map(),.filter(), or.reduce()on them unless you convert them to an array first usingArray.from(nodeList)or[...nodeList].
Interview Questions
Q:
What is the difference between
querySelector and querySelectorAll?A:
querySelector scans the DOM and returns the very first element that matches the CSS selector. querySelectorAll returns a NodeList containing every single element on the page that matches the selector.
Real-World Example
Selecting a form input so you can read its value when a user clicks submit.
example
javascript
const emailInput = document.querySelector('#email');
console.log(emailInput.value);Check Your Knowledge
Test your understanding of Selecting Elements with these quick questions.