What is the DOM in JavaScript?
DOM stands for Document Object Model. It is a programming interface for web documents that allows JavaScript to interact with, modify, and control HTML and CSS dynamically.
DOM: Simple Definition
The DOM represents the structure of a webpage as a tree of nodes (objects), where each HTML element becomes a JavaScript object that you can access and manipulate.
Real-World Analogy
Imagine an HTML page is like a tree, and each tag (like <p>, <div>, <h1>) is a branch or leaf. JavaScript can climb this tree, find elements, and change their content, style, or behavior.
DOM Tree Example
Given this HTML
<!DOCTYPE html>
<html>
<head><title>My Page</title></head>
<body>
<h1 id= "title" Hello</h1>
<p class="text">Welcome to JavaScript DOM!</p>
</body>
</html>
This becomes a DOM tree where:
- document is the root object
- document.body accesses the <body>
- document.getElementById("title") accesses the <h1>
JavaScript and DOM Manipulation
Access Elements
const heading = document.getElementById("title");
const paragraph = document.querySelector(".text");
Change Content
heading.textContent = "Welcome!";
Change Style
paragraph.style.color = "blue";
Add/Remove HTML
paragraph.innerHTML ="<strong>Updated</strong> text!";
Common DOM Methods
Method | Description |
---|---|
getElementById() | Select by ID |
getElementsByClassNam e() | Select by class (HTMLCollection) |
querySelector() | Select first match (CSS selector) |
querySelectorAll() | Select all matches (NodeList) |
createElement() | Create new HTML element |
appendChild() | Add child element |
removeChild() | Remove child element |
Event Handling with DOM
const btn = document.querySelector("button");
btn.addEventListener("click", function () {
alert("Button clicked!");
});
Why DOM is Important
- Enables dynamic user interfaces
- Lets JavaScript change web content without reloading the page
- Forms the core of all interactive web apps