Problem Statement
What is the difference between getElementById and querySelector?
Explanation
GetElementById selects a single element by its ID attribute. It is faster because it directly uses the browser's optimized ID lookup. It returns the element or null if not found.
QuerySelector uses CSS selector syntax and is more flexible. You can select by ID, class, attribute, or any CSS selector. It returns the first matching element or null.
QuerySelector is slower but more powerful. Use getElementById when selecting by ID for better performance. Use querySelector when you need CSS selector flexibility.
Both return a single element. For multiple elements, use getElementsByClassName or querySelectorAll.
Understanding DOM selection methods is fundamental to JavaScript web development.
Code Solution
SolutionRead Only
// getElementById - fast, ID only
const header = document.getElementById('header');
console.log(header); // <div id="header">...</div>
// Must use ID without #
// const wrong = document.getElementById('#header'); // Wrong!
// querySelector - flexible, any CSS selector
const header2 = document.querySelector('#header');
const firstButton = document.querySelector('button');
const activeItem = document.querySelector('.item.active');
const input = document.querySelector('input[type="email"]');
// querySelector returns first match only
const buttons = document.querySelectorAll('button'); // All buttons
console.log(buttons.length); // e.g., 5
const firstBtn = document.querySelector('button'); // First button only
// Performance comparison
console.time('getElementById');
for (let i = 0; i < 10000; i++) {
document.getElementById('header');
}
console.timeEnd('getElementById'); // Faster
console.time('querySelector');
for (let i = 0; i < 10000; i++) {
document.querySelector('#header');
}
console.timeEnd('querySelector'); // Slower
// Complex selectors with querySelector
const nested = document.querySelector('div.container > p.text');
const nthChild = document.querySelector('li:nth-child(3)');
const notClass = document.querySelector('div:not(.excluded)');
// Other selection methods
const byClass = document.getElementsByClassName('item'); // HTMLCollection
const byTag = document.getElementsByTagName('p'); // HTMLCollection
const allDivs = document.querySelectorAll('div'); // NodeList
// Difference: HTMLCollection vs NodeList
// HTMLCollection is live, NodeList from querySelectorAll is static
const liveList = document.getElementsByClassName('item');
const staticList = document.querySelectorAll('.item');
console.log(liveList.length); // e.g., 3
console.log(staticList.length); // e.g., 3
// Add new element with class 'item'
document.body.innerHTML += '<div class="item">New</div>';
console.log(liveList.length); // 4 (updated automatically!)
console.log(staticList.length); // 3 (stays same)