π§© Understanding the DOM: How JavaScript Interacts with HTML


When you open a webpage in your browser, what you actually see is not just raw HTML code. Instead, your browser creates a Document Object Model (DOM) β a structured representation of the page. JavaScript uses this model to dynamically interact with, modify, and control the web page.
π What is the DOM?
The DOM (Document Object Model) is a tree-like structure that represents the elements of an HTML page. Each element (like <div>
, <p>
, <h1>
, etc.) is a node in the DOM.
π Think of the DOM as a bridge between HTML and JavaScript. While HTML defines the structure, JavaScript uses the DOM to read and manipulate that structure.
πΌοΈ DOM Tree Structure
Hereβs a simple diagram of how an HTML document is represented in the DOM:
HTML
βββ HEAD
β βββ TITLE
β βββ "My Page"
βββ BODY
βββ H1
β βββ "Hello World"
βββ P
βββ "This is a paragraph."
Each tag becomes a node, and nested tags form parent-child relationships.
βοΈ How JavaScript Interacts with the DOM
JavaScript can access and change DOM elements using built-in methods.
Example HTML:
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello World</h1>
<p>This is a paragraph.</p>
</body>
</html>
Example JavaScript:
// Select the element
const heading = document.getElementById("title");
// Change its content
heading.textContent = "DOM Manipulated by JavaScript!";
// Change its style
heading.style.color = "blue";
Result:
The text in <h1>
will change to blue and say "DOM Manipulated by JavaScript!".
π Key Points to Remember
The DOM represents HTML as a tree of objects.
JavaScript can select, modify, add, or remove elements from the DOM.
Changes made via JavaScript are immediately visible on the web page.
DOM manipulation is the foundation for dynamic and interactive web applications.
π Conclusion
The DOM is what makes web pages interactive. Without it, HTML would remain static. By understanding how the DOM works, developers can create everything from simple text updates to complex dynamic applications like real-time dashboards, games, and modern single-page apps.
Subscribe to my newsletter
Read articles from Deepansh Vishwakarma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
