The Document Object Model (DOM)
18 min read
DOMDOM TreeNode TypesDOM APITraversalManipulation
The DOM: Your HTML as a Living Object
When the browser loads HTML, it creates a tree of objects called the Document Object Model. Every HTML element becomes a node you can read, modify, and delete with JavaScript.
Node Types
| Type | Value | Example |
|---|---|---|
| Element Node | 1 | <div>, <p> |
| Text Node | 3 | Text inside elements |
| Comment Node | 8 | <!-- comment --> |
| Document Node | 9 | The root document |
DOM Traversal
- Parent: element.parentNode / element.parentElement
- Children: element.children (elements only) vs element.childNodes (all nodes)
- Siblings: element.nextElementSibling / element.previousElementSibling
Selection Methods Performance
| Method | Returns | Live? | Speed |
|---|---|---|---|
| getElementById | Single element | N/A | Fastest |
| querySelector | First match | No | Fast |
| querySelectorAll | NodeList | No (static) | Fast |
| getElementsByClassName | HTMLCollection | Yes (live) | Fast |
| getElementsByTagName | HTMLCollection | Yes (live) | Fast |
Live vs Static Collections
A live HTMLCollection updates automatically when the DOM changes. A static NodeList (from querySelectorAll) is a snapshot. Modifying the DOM while iterating a live collection causes bugs!
DocumentFragment for Batch Updates
Instead of appending 100 elements one by one (100 reflows), create them inside a DocumentFragment (0 reflows) and append the fragment once (1 reflow).