Dom Intro in JavaScript
? DOM Intro in JavaScript
What is the DOM?
DOM stands for Document Object Model.
It is a programming interface for HTML and XML documents.
The DOM represents a page so that programs can change the structure, style, and content of a web page dynamically.
Think of it as a tree of objects where each node is an element, attribute, or piece of text in the HTML document.
Why is DOM Important?
JavaScript uses the DOM to interact with the webpage after it has loaded.
You can:
Access elements on the page
Change their content or styles
Add or remove elements
React to user actions (clicks, inputs, etc.)
How DOM Works?
When a browser loads a web page, it parses the HTML and creates the DOM tree.
This tree is a structured representation of all elements in the document.
JavaScript accesses this tree via the
documentobject.
Basic Example
<!DOCTYPE html><html> <body> <h1 id="title">Hello World!</h1> <button id="btn">Click Me</button> <script> // Access the DOM element const title = document.getElementById("title"); // Change the text content title.textContent = "Hello from DOM!"; // Add a click event to the button const button = document.getElementById("btn"); button.addEventListener("click", () => { alert("Button clicked!"); }); </script> </body></html>Key DOM Objects
| Object | Description |
|---|---|
document | Represents the whole webpage |
element | Represents any HTML element |
node | A generic term for any object in the DOM tree (elements, text, comments) |
window | Represents the browser window |
Summary
The DOM is the bridge between HTML and JavaScript.
It allows JavaScript to read and manipulate the page dynamically.
Almost everything you do with JS on a webpage involves interacting with the DOM.
Want to dive into DOM manipulation, event handling, or traversing the DOM tree next?