Topic 27 of 37
The DOM & Selectors
Overview
The Document Object Model (DOM) is a tree-like representation of your HTML document that the browser creates. Web APIs (provided by the browser, not the JS engine) allow JavaScript to interact with this tree to read, change, or delete elements dynamically.
Syntax
Always prefer querySelector/querySelectorAll over older methods like getElementById unless performance is a micro-optimization bottleneck.
Modern DOM Selectors
javascript
// Selects the FIRST element matching the CSS selector
const button = document.querySelector('.btn-primary');
// Selects ALL elements matching the CSS selector (returns NodeList)
const allLinks = document.querySelectorAll('a[target="_blank"]');
// Modifying elements
button.textContent = "Click Me!";
button.classList.add('active');
button.style.backgroundColor = "blue";Common Pitfalls
- Accessing DOM elements before the HTML is parsed. Always put script tags at the bottom of the body or use the 'defer' attribute.
Interview Tips
- Explain the difference between a NodeList (returned by querySelectorAll) and a live HTMLCollection (returned by getElementsByClassName).
Real-World Example
Creating a dark mode toggle.
example
javascript
const themeBtn = document.querySelector('#theme-toggle');
themeBtn.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
});