What is the DOM?
Overview
The DOM (Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.
When a browser loads an HTML file, it converts the raw text into a hierarchical 'Tree of Objects'. Each HTML element becomes a 'Node' in this tree. JavaScript uses the global document object to interact with this tree, allowing us to build dynamic, interactive websites instead of static pages.
Syntax
// The 'document' object is globally available in the browser
console.log(document.title); // Reads the <title> tag
// Modify the title dynamically
document.title = "New Page Title!";
// Check the body
console.log(document.body); // Returns the entire <body> nodeCommon Pitfalls
- Trying to access DOM elements before they have rendered. If you place a
<script>tag in the<head>without thedeferattribute, your JavaScript will run before the HTML body exists, meaningdocument.bodywill benulland your code will crash.
Interview Questions
No. The DOM is a Web API provided by the browser (like Chrome or Firefox). JavaScript is simply the language we use to interact with this API. This is why the document object doesn't exist in backend Node.js environments.
Real-World Example
React uses a 'Virtual DOM'. It creates a lightweight copy of the real DOM in memory, calculates the fastest way to make changes, and then updates the real DOM efficiently.
// A mental model of React's process
const virtualDom = { tag: 'div', children: 'Hello' };
// React compares virtual to real, then updates real efficiently.Check Your Knowledge
Test your understanding of What is the DOM? with these quick questions.