Efficient DOM Selection Techniques Every Frontend Developer Should Know
Abdelatif Baha
Paris, FRANCE
Mastering DOM Selection
Selecting DOM elements efficiently is fundamental to frontend development. Modern JavaScript provides multiple methods, each with its own use cases and performance implications.
The Classic Methods
getElementById
The fastest selection method:
const element = document.getElementById('myId');
getElementsByClassName
Returns a live HTMLCollection:
const elements = document.getElementsByClassName('myClass');
Modern Query Methods
querySelector
Returns the first matching element:
const element = document.querySelector('.container > .item:first-child');
querySelectorAll
Returns a static NodeList:
const elements = document.querySelectorAll('.item');
elements.forEach(el => console.log(el));
Performance Considerations
- ID selection is fastest - Use
getElementByIdwhen possible - querySelector is flexible - Great for complex selectors
- Live vs Static collections - Understand the difference
- Cache selections - Don't query the same element repeatedly
Best Practices
// ❌ Bad - Multiple queries
document.querySelector('.btn').addEventListener('click', () => {
document.querySelector('.result').textContent = 'Clicked';
});
// ✅ Good - Cached selection
const btn = document.querySelector('.btn');
const result = document.querySelector('.result');
btn.addEventListener('click', () => {
result.textContent = 'Clicked';
});
Modern Alternatives in React/Next.js
In React and Next.js, use refs for direct DOM access:
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
Conclusion
Choosing the right DOM selection method improves both code readability and performance. Know your options and use them wisely!
Comments (0)