What is the DOM?
The Document Object Model (DOM) is a representation of your HTML page that JavaScript can interact with. You can select, modify, and delete elements.
💡 Key insight
The DOM is like a tree structure where each HTML element is a node. JavaScript gives you tools to navigate and manipulate this tree.
Selecting Elements
document.getElementById('id')— selects by ID (returns one element)document.querySelector('.class')— selects the first matching elementdocument.querySelectorAll('.class')— selects all matching elements (returns NodeList)document.getElementsByClassName('class')— selects by class (returns HTMLCollection)document.getElementsByTagName('div')— selects by tag name
Common Mistakes
- Running DOM selection before the DOM is loaded (use
DOMContentLoaded) - Using
querySelectorAllbut expecting a single element - Using
getElementsByClassNamewhich returns a live HTMLCollection
Quick Quiz
1. Which method selects elements by ID?
2. Which method returns all matching elements?
3. What does document.querySelector('.class') return?
Summary
getElementById()— selects by ID (one element)querySelector()— selects first matching elementquerySelectorAll()— selects all matching elements (NodeList)getElementsByClassName()— selects by class (HTMLCollection)- Use
DOMContentLoadedto ensure the DOM is ready
