**querySelector** and **querySelectorAll** are the modern standard for selecting DOM elements — they accept any CSS selector. **getElementById** is faster for single ID lookups. **getElementsByClassName** and **getElementsByTagName** return **live HTMLCollections** (update when DOM changes), while querySelectorAll returns a **static NodeList**.
1Understanding Element Selection
querySelector and querySelectorAll are the modern standard for selecting DOM elements — they accept any CSS selector. getElementById is faster for single ID lookups. getElementsByClassName and getElementsByTagName return live HTMLCollections (update when DOM changes), while querySelectorAll returns a static NodeList.
querySelectorAll returns a static NodeList, not an array. Use Array.from() or [...nodeList] to use array methods.
// Modern selection methods
const title = document.querySelector('h1');
const buttons = document.querySelectorAll('.btn');
const nav = document.getElementById('main-nav');
console.log(title.textContent);
console.log(buttons.length);
// Convert NodeList to array
const btnArray = Array.from(buttons);
btnArray.filter(btn => btn.disabled).forEach(btn => {
console.log(btn.id + ' is disabled');
});2Practical Example
Here is a real-world application of Element Selection showing how it is used in production JavaScript code.
// Context-based selection (scope to a parent)
const form = document.querySelector('#loginForm');
const inputs = form.querySelectorAll('input');
// Only searches within #loginForm!3Best Practices
Follow these guidelines when working with Element Selection:
1. Use querySelector/querySelectorAll for flexible CSS selector queries
2. Use getElementById for the fastest single-element ID lookup
3. Convert NodeList to array with Array.from() for filtering
Tip: querySelectorAll returns a static NodeList, not an array. Use Array.from() or [...nodeList] to use array methods.
// Modern selection methods
const title = document.querySelector('h1');
const buttons = document.querySelectorAll('.btn');
const nav = document.getElementById('main-nav');
console.log(title.textContent);
console.log(buttons.length);
// Convert NodeList to array
const btnArray = Array.from(buttons);
btnArray.filter(btn => btn.disabled).forEach(btn => {
console.log(btn.id + ' is disabled');
});