JavaScript Notes
Master all DOM element selection methods in JavaScript. Compare querySelector vs getElementById, understand live HTMLCollections vs static NodeLists, and learn advanced CSS selectors with real examples.
Overview: All Selection Methods at a Glance
Before writing any code, here is the full picture of what tools you have:
DOM Selection Methods — Quick Reference:
══════════════════════════════════════════════════════════════════
Method │ Returns │ Live? │ Speed
══════════════════════════════════════════════════════════════════
getElementById('id') │ Element or null │ N/A │ ⚡ Fastest
querySelector('css') │ Element or null │ N/A │ 🔶 Fast
querySelectorAll('css') │ NodeList (static) │ No │ 🔶 Fast
getElementsByClassName('cls') │ HTMLCollection │ Yes │ 🔷 Fast
getElementsByTagName('tag') │ HTMLCollection │ Yes │ 🔷 Fast
getElementsByName('name') │ NodeList │ Yes │ 🔶 Moderate
══════════════════════════════════════════════════════════════════querySelector() — CSS Selector for First Match
Returns the first element matching any valid CSS selector. Incredibly flexible.
"HEADER" "First Article" "Home" "First Article" "101" "Home" "About" "science" "About"
querySelectorAll() — Select Multiple Elements (Static NodeList)
Returns all matching elements as a static NodeList (like a frozen snapshot).
3 true 1 0: Home → / 1: About → /about 2: Contact → /contact "Active links: 1" 2 2 3
getElementsByClassName() — LIVE HTMLCollection
Returns a live HTMLCollection — it automatically updates when the DOM changes.
3 4 Home About Contact Blog "Home"
Live HTMLCollection vs Static NodeList — Critical Difference
const container = document.querySelector('#container');
// LIVE collection
const liveItems = document.getElementsByTagName('h2');
console.log('Live before:', liveItems.length); // 2
// STATIC snapshot
const staticItems = document.querySelectorAll('h2');
console.log('Static before:', staticItems.length); // 2
// Add a new h2
const newH2 = document.createElement('h2');
newH2.textContent = 'Third Article';
container.appendChild(newH2);
console.log('Live after:', liveItems.length); // 3 ← updated!
console.log('Static after:', staticItems.length); // 2 ← unchanged!Live before: 2 Static before: 2 Live after: 3 Static after: 2
Scoped Queries — Search Within an Element
All selector methods can run on any element, not just document:
const main = document.querySelector('main');
// Search only INSIDE main, not the whole document
const articlesInMain = main.querySelectorAll('article');
console.log(articlesInMain.length); // 2
// getElementById only works on document, not elements
// main.getElementById('...') → TypeError!
// But querySelector works on any element
const firstExcerpt = main.querySelector('.excerpt');
console.log(firstExcerpt.textContent); // "Tech article preview..."
// Great for component-style code
function getLinks(parentEl) {
return parentEl.querySelectorAll('a');
}
const navLinks = getLinks(document.querySelector('nav'));
console.log(navLinks.length); // 32 "Tech article preview..." 3
CSS Selector Quick Reference for querySelector
Real World Use Cases
Common Mistakes
❌ Mistake 1: Using # in getElementById
// ❌ Wrong — # is CSS selector syntax
document.getElementById('#myDiv'); // Returns null!
// ✅ Correct
document.getElementById('myDiv'); // Returns the element❌ Mistake 2: Calling .forEach() on HTMLCollection
❌ Mistake 3: Infinite loop with live collection
Interview Questions
Q1. What is the difference between querySelector and getElementById? > getElementById accepts only an ID string (no #) and is the fastest selector. querySelector accepts any CSS selector, is more flexible, but slightly slower. Use getElementById when you know the ID, querySelector for complex selectors.
Q2. What is the difference between a live HTMLCollection and a static NodeList? > A live HTMLCollection (returned by getElementsByClassName, getElementsByTagName) automatically updates when the DOM changes. A static NodeList (returned by querySelectorAll) is a snapshot that doesn't change after creation.
Q3. Can querySelectorAll be called on an element (not just document)? > Yes! Any element can be used as the search root: myDiv.querySelectorAll('p') finds all <p> elements inside myDiv. This is useful for component-scoped queries.
Q4. Why might getElementsByClassName cause an infinite loop? > Because it returns a LIVE collection. If you add elements with the same class during iteration, the collection grows and the loop never ends. Convert to an array first to avoid this.
Q5. What does querySelectorAll return if nothing matches? > An empty NodeList (not null). So it's safe to call .forEach() on the result without a null check: document.querySelectorAll('.missing').forEach(...) won't throw.
Q6. Which is faster: getElementById or querySelector('#id')? > getElementById is faster because the browser maintains an internal ID hash map for O(1) lookup. querySelector must evaluate the CSS selector engine. Benchmarks show getElementById can be 2-5x faster.
Q7. How do you select elements with multiple specific classes? > Chain the classes in the selector with no space: querySelector('.btn.primary.large'). This selects elements that have ALL three classes.
Key Takeaways
✅ getElementById is fastest — use it when you have an ID
✅ querySelector is most flexible — accepts any CSS selector
✅ querySelectorAll returns STATIC NodeList — snapshot, not live
✅ getElementsByClassName/TagName return LIVE HTMLCollection
✅ NodeList has .forEach() but HTMLCollection does NOT
✅ Convert HTMLCollection to Array before using array methods
✅ querySelector can be scoped to any element, not just document
✅ querySelectorAll returns empty NodeList (not null) on no match
✅ Live collections can cause infinite loops — convert firstExam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript DOM Selecting Elements - querySelector, getElementById Complete Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, dom, selecting, elements
Related JavaScript Master Course Topics