Document Object Model
What is DOM and What is its use?
What is DOM?
The Document Object Model (DOM) is a programming interface for HTML and XML documents.
It represents the structure of a web page as a hierarchical tree of objects (called nodes), where each node corresponds to a part of the document—such as elements, text, and attributes.
Why DOM Matters:
Without the DOM, web pages would be static and unable to respond to user interactions dynamically. The DOM abstracts the document structure into objects that developers can programmatically manipulate using JavaScript. This enables features like dynamic content updates, animations, interactive forms, and more.
DOM Hierarchy Structure
The DOM models the document as a tree of nodes. Each HTML element becomes a node, and relationships between elements become parent-child connections.
Example HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h1>Page Title</h1>
<p>This is a paragraph.</p>
<div>
<span>A nested span element.</span>
</div>
</body>
</html>Visual Representation of the DOM Tree:
Document (root)
├── html
├── head
│ └── title
└── body
├── h1
├── p
└── div
└── spanThe root node of the DOM tree is the document, which is different from the global window object.
Static HTML
Static HTML consists of content that is fixed and does not change unless the entire page is reloaded.
Example of Static HTML:
<!DOCTYPE html>
<html>
<head>
<title>Static Page</title>
</head>
<body>
<h1>Welcome to My Static Website</h1>
<p>This content never changes unless the developer updates the code.</p>
</body>
</html>Drawback:
User interactions (like form submissions or button clicks) require full page reloads, which is slow and inefficient.
Dynamic HTML
Dynamic HTML (DHTML) allows the page content to be updated on-the-fly without reloading the entire page.
Example of Dynamic HTML:
<button onclick="updateText()">Click Me</button>
<p id="dynamic-text">Original Text</p>
<script>
function updateText() {
document.getElementById('dynamic-text').innerHTML = 'Text updated dynamically!';
}
</script>Fetching Elements
Common Methods:
document.getElementById('id')document.querySelector('selector')document.querySelectorAll('selector')document.getElementsByClassName('class')document.getElementsByTagName('tag')
Example:
<h1 id="main-heading">Main Heading</h1>
<script>
const heading = document.getElementById('main-heading');
console.log(heading.textContent); // Outputs: "Main Heading"
</script>Updating Elements
Example 1: Change Text Content
<p id="my-paragraph">Old Content</p>
<button onclick="changeContent()">Change Text</button>
<script>
function changeContent() {
const para = document.getElementById('my-paragraph');
para.textContent = 'New content after update!';
}
</script>Example 2: Change Attributes
<img id="my-image" src="image1.jpg" alt="Old Image">
<script>
const image = document.getElementById('my-image');
image.src = 'image2.jpg';
image.alt = 'Updated Image';
</script>Deleting Elements
Example 1: Direct Removal
<div id="container">
<p id="remove-me">This paragraph will be removed.</p>
</div>
<button onclick="deleteElement()">Delete Paragraph</button>
<script>
function deleteElement() {
const element = document.getElementById('remove-me');
element.remove();
}
</script>Example 2: Remove Child via Parent
<div id="parent">
<p id="child">Child paragraph</p>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.removeChild(child);
</script>Example 3: Remove Element Using parentNode.removeChild()
<div id="container">
<p id="remove-me">This paragraph will be removed using parentNode.removeChild()</p>
</div>
<button onclick="removeUsingParent()">Remove via Parent Node</button>
<script>
function removeUsingParent() {
const element = document.getElementById('remove-me');
element.parentNode.removeChild(element);
}
</script>Creating Elements
How to Create Elements
- Use
document.createElement('tagName')to create a new element node. - Set properties like
textContent,className,id, or attributes usingsetAttribute(). - Append the element into the DOM tree using
appendChild(),insertBefore(), or other insertion methods.
Example 1: Simple Element Creation
<button onclick="createParagraph()">Create Paragraph</button>
<script>
function createParagraph() {
const newPara = document.createElement('p');
newPara.textContent = 'This is a dynamically created paragraph.';
document.body.appendChild(newPara);
}
</script>Example 2: Set Attributes and Style
<button onclick="createStyledElement()">Create Styled Element</button>
<script>
function createStyledElement() {
const newDiv = document.createElement('div');
newDiv.textContent = 'Styled Div';
newDiv.setAttribute('id', 'styled-div');
newDiv.className = 'my-class';
newDiv.style.backgroundColor = 'lightblue';
newDiv.style.padding = '10px';
document.body.appendChild(newDiv);
}
</script>Adding Elements
Example: Adding a New Element
<button onclick="addDiv()">Add Div</button>
<script>
function addDiv() {
const newDiv = document.createElement('div');
newDiv.textContent = 'This is a dynamically added div!';
newDiv.style.color = 'blue';
document.body.appendChild(newDiv);
}
</script>More Complex Elements
Example: Dynamic List Creation
<button onclick="createList()">Create List</button>
<script>
function createList() {
const list = document.createElement('ul');
list.style.border = '1px solid #000';
list.style.padding = '10px';
for (let i = 1; i <= 3; i++) {
const listItem = document.createElement('li');
listItem.textContent = `List Item ${i}`;
list.appendChild(listItem);
}
document.body.appendChild(list);
}
</script>DocumentFragment – Optimize DOM Manipulation
What Is DocumentFragment?
A DocumentFragment is a lightweight container for DOM nodes that exists in memory but is not part of the main DOM tree.
It allows you to perform multiple DOM manipulations without causing multiple reflows and repaints.
Why Use DocumentFragment?
Without DocumentFragment, adding elements one by one to the DOM causes the browser to reflow and repaint each time, slowing performance.
Using DocumentFragment, you batch your changes and append them in one go.
Example Without DocumentFragment (Poor Performance):
for (let i = 1; i <= 1000; i++) {
const listItem = document.createElement('li');
listItem.textContent = `Item ${i}`;
document.body.appendChild(listItem); // Repaints every time
}Example With DocumentFragment (Optimized):
const fragment = document.createDocumentFragment();
for (let i = 1; i <= 1000; i++) {
const listItem = document.createElement('li');
listItem.textContent = `Item ${i}`;
fragment.appendChild(listItem); // No repaint yet
}
document.body.appendChild(fragment); // One single repaint