DOM in 5 min

What is DOM?
The DOM (Document Object Model) is an essential concept in web development, representing the structure of an HTML or XML document as an object-oriented tree. Here's a concise explanation of its key points:
1. What is the DOM?
The DOM is a programming interface that allows scripts (usually JavaScript) to interact with HTML or XML documents. It provides a structured, dynamic way of accessing and modifying the content, structure, and style of web pages.
2. How the DOM Works:
When a web page is loaded in a browser, the browser creates a DOM of the page. This DOM is a tree-like structure where:
Each element (like
<div>
,<p>
,<a>
) becomes a node in the tree.Attributes (like
id
,class
) of elements become properties of those nodes.Text inside the elements is also a node.
3. DOM Nodes & Elements:
Element Nodes: Represent HTML tags (like
<div>
).Text Nodes: Contain the text inside elements (like the content inside a
<p>
tag).Attribute Nodes: Represent attributes of elements (like
src
in an<img>
tag).Comment Nodes: Represent comments in the code.
4. Manipulating the DOM with JavaScript:
JavaScript can be used to interact with the DOM. Common operations include:
Accessing elements:
document.getElementById('myId')
ordocument.querySelector('.myClass')
.Modifying content:
element.innerHTML = 'New content';
changes the inner content of an element.Changing styles:
element.style
.color = 'red';
changes the text color.Adding/removing elements: You can dynamically create, remove, or change elements with methods like
document.createElement()
orparentNode.removeChild()
.
5. Event Handling:
The DOM allows interaction with users through events. For example, a button click or a mouse hover can trigger an event. You can listen to these events using JavaScript like this:
javascriptCopydocument.getElementById('myButton').addEventListener('click', function() {
alert('Button clicked!');
});
6. Real-Time Updates:
Since the DOM is dynamic, any changes made to it (like modifying text or adding elements) immediately affect the rendered page. This is key for creating interactive web applications.
In Summary:
The DOM is a tree-like structure representing a web page's content.
JavaScript interacts with the DOM to manipulate and update the page dynamically.
Node Types include elements, text, and attributes.
The DOM makes web pages interactive by enabling event handling.
The DOM allows developers to create dynamic, interactive websites by modifying the page in real time based on user input or other factors.
Subscribe to my newsletter
Read articles from Tanushree Borase directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Tanushree Borase
Tanushree Borase
I am a college student and eager to share my knowledge and experiences with other fellow coders. Lets connect and enhance our Knowledge!!