What is the DOM?
The DOM (Document Object Model) is a tree representation of an HTML page. JavaScript uses the DOM to read, modify, add, and delete HTML elements. Every element on the page is a 'node' in this tree.
DOM Explained
- DOM — A programming interface for HTML. Browser converts HTML into a tree of objects
- document — The root object. Entry point to the DOM: document.body, document.title
- Nodes — Everything in the DOM is a node: elements, text, attributes, comments
- Element node — HTML tags: <div>, <p>, <h1>. Most commonly manipulated
- Text node — The text content inside elements
- DOM tree — html → head + body → nested elements. Parent → child → sibling relationships
DOM Tree Visual
// The DOM represents this HTML as a tree:
// <html>
// <head><title>My Page</title></head>
// <body>
// <h1>Hello</h1>
// <p>World</p>
// </body>
// </html>
// DOM tree:
// document
// └── html
// ├── head
// │ └── title → "My Page"
// └── body
// ├── h1 → "Hello"
// └── p → "World"
// Access DOM properties
console.log(document.title); // "My Page"
console.log(document.body); // <body> element
console.log(document.documentElement); // <html> element
// Navigate the tree
// element.parentNode → parent
// element.children → child elements
// element.firstElementChild / lastElementChild
// element.nextElementSibling / previousElementSiblingTip
Tip
Think of the DOM as a live representation of your HTML. Changes to the DOM instantly update the page. Use document.querySelector() to select elements and then modify their properties, styles, or content programmatically.
The DOM represents HTML as a tree of nodes that JavaScript can manipulate
Common Mistake
Warning
Trying to access DOM elements before the page loads. Scripts in <head> run before the body exists. Use defer attribute on script tags or place scripts before </body> to ensure all elements are available.
Practice Task
Note
Explore the DOM in DevTools: (1) Open F12 > Elements tab and inspect any element. (2) In Console, try document.querySelector('body').children to see child elements. (3) Use document.title = 'New Title' to change the page title live.
Quick Quiz
Key Takeaways
- The DOM (Document Object Model) is a tree representation of an HTML page.
- DOM — A programming interface for HTML. Browser converts HTML into a tree of objects
- document — The root object. Entry point to the DOM: document.body, document.title
- Nodes — Everything in the DOM is a node: elements, text, attributes, comments