DOM Manipulation is one of the most important concepts in JavaScript. It allows developers to access, modify, add, and remove HTML elements dynamically after a webpage has loaded.
The Document Object Model (DOM) creates a connection between JavaScript and HTML documents. Using DOM methods, JavaScript can change webpage content, styles, attributes, and structure according to user actions.
Interactive websites, dashboards, forms, animations, and modern web applications heavily depend on DOM manipulation.
DOM stands for Document Object Model. It is a programming interface that represents an HTML document as a collection of objects.
When a browser loads an HTML page, it converts the complete document into a tree-like structure called the DOM Tree.
JavaScript uses this tree structure to access and control webpage elements.
HTML creates the structure of a webpage, CSS controls the design, and JavaScript adds behavior. DOM acts as a bridge between JavaScript and HTML.
The browser represents HTML elements in the form of a tree structure.
<html>
<body>
<h1>
Heading
</h1>
<p>
Paragraph
</p>
</body>
</html>
The DOM structure looks like:
Document
└── html
└── body
├── h1
└── p
The document object represents the entire HTML page loaded in the browser.
JavaScript uses this object to access HTML elements.
document.write("Hello JavaScript");
Hello JavaScript
Before modifying any HTML element, JavaScript needs to select that element.
JavaScript provides several methods for selecting elements.
The getElementById() method selects an element using its unique id attribute.
document.getElementById("id-name");
<p id="message">
Hello
</p>
<script>
let text =
document.getElementById("message");
console.log(text);
</script>
This method selects multiple elements having the same class name.
document.getElementsByClassName("class-name");
let items =
document.getElementsByClassName("box");
This method selects elements using HTML tag names.
let paragraphs =
document.getElementsByTagName("p");
The querySelector() method selects the first matching element using CSS selectors.
let heading =
document.querySelector("h1");
The querySelectorAll() method selects all matching elements.
let buttons =
document.querySelectorAll("button");
| Method | Purpose |
|---|---|
| getElementById() | Select single element by id. |
| getElementsByClassName() | Select elements by class. |
| getElementsByTagName() | Select elements by tag. |
| querySelector() | Select first matching CSS selector. |
| querySelectorAll() | Select all matching CSS selectors. |
JavaScript can modify webpage text and HTML content using DOM properties.
The innerHTML property is used to change the HTML content inside an element.
<p id="demo">
Old Text
</p>
<script>
document.getElementById("demo")
.innerHTML="New Text";
</script>
New Text
The innerText property changes only visible text content.
document.getElementById("demo")
.innerText="Welcome JavaScript";
JavaScript DOM allows developers to change the style of HTML elements dynamically. Using the DOM style property, we can modify colors, sizes, backgrounds, fonts, and many other CSS properties while the webpage is running.
Dynamic styling is commonly used for animations, themes, interactive buttons, and user interface improvements.
The style property is used to access and modify CSS styles of selected elements.
element.style.property = "value";
<p id="text">
JavaScript DOM
</p>
<script>
let paragraph =
document.getElementById("text");
paragraph.style.color = "blue";
</script>
JavaScript DOM (Text color changes to blue)
let box =
document.getElementById("box");
box.style.backgroundColor = "yellow";
The background color of the selected element changes dynamically.
let heading =
document.querySelector("h1");
heading.style.fontSize = "40px";
Multiple styles can be modified using DOM.
let element =
document.getElementById("demo");
element.style.color="green";
element.style.backgroundColor="black";
element.style.padding="20px";
Instead of changing every style property individually, JavaScript can add, remove, or toggle CSS classes using the classList property.
The add() method adds a new CSS class to an element.
let box =
document.getElementById("box");
box.classList.add("active");
The remove() method removes an existing CSS class.
box.classList.remove("active");
The toggle() method adds a class if it does not exist and removes it if it already exists.
box.classList.toggle("dark");
The contains() method checks whether an element contains a specific class.
let result =
box.classList.contains("active");
console.log(result);
HTML elements contain attributes such as id, class, src, href, and title. JavaScript can modify these attributes dynamically.
The getAttribute() method is used to read the value of an attribute.
let image =
document.getElementById("photo");
let source =
image.getAttribute("src");
console.log(source);
The setAttribute() method is used to add or update an attribute value.
let image =
document.getElementById("photo");
image.setAttribute(
"src",
"newimage.jpg"
);
The removeAttribute() method removes an attribute from an HTML element.
button.removeAttribute("disabled");
JavaScript can create new HTML elements dynamically using DOM methods.
This feature is useful for adding new content without refreshing the webpage.
The createElement() method creates a new HTML element.
document.createElement("tag-name");
let heading =
document.createElement("h2");
heading.innerHTML =
"Welcome to CSE Gyan";
The appendChild() method adds a new element as the last child of another element.
let paragraph =
document.createElement("p");
paragraph.innerHTML =
"New Paragraph";
document.body.appendChild(paragraph);
New Paragraph
The insertBefore() method inserts a new element before an existing element.
parent.insertBefore( newElement, existingElement );
JavaScript allows removing unwanted elements from the webpage dynamically.
The removeChild() method removes a child element from its parent.
let item =
document.getElementById("item");
item.parentNode.removeChild(item);
Modern JavaScript provides the remove() method to directly delete an element.
let element =
document.getElementById("box");
element.remove();
The replaceChild() method replaces an existing element with a new element.
parent.replaceChild( newElement, oldElement );
DOM navigation allows accessing related elements such as parents, children, and siblings.
| Property | Description |
|---|---|
| parentNode | Returns parent element. |
| childNodes | Returns child elements. |
| firstChild | Returns first child. |
| lastChild | Returns last child. |
| nextSibling | Returns next element. |
| previousSibling | Returns previous element. |
let child =
document.getElementById("child");
console.log(
child.parentNode
);
DOM manipulation becomes more powerful when combined with JavaScript events.
Users can interact with webpage elements, and JavaScript can modify the DOM according to those actions.
Hello User
Forms are an important part of modern websites. JavaScript DOM allows developers to access form elements, read user input, validate information, and update form values dynamically.
Login pages, registration forms, search boxes, feedback forms, and payment systems commonly use DOM form manipulation.
JavaScript can access form elements using DOM selection methods like getElementById(), querySelector(), and form collections.
<input type="text" id="username">
<script>
let user =
document.getElementById("username");
console.log(user);
</script>
The value property is used to read data entered by the user.
<input type="text" id="name">
<script>
let username =
document.getElementById("name").value;
console.log(username);
</script>
JavaScript can also update input values dynamically.
document.getElementById("name")
.value = "CSE Gyan";
Form validation ensures that users enter correct and complete information before submitting data.
function checkForm()
{
let name =
document.getElementById("name").value;
if(name=="")
{
alert("Please Enter Name");
}
else
{
alert("Form Submitted");
}
}
JavaScript can create and update lists dynamically without modifying HTML manually.
Dynamic lists are used in shopping carts, task managers, search suggestions, and notification systems.
let list =
document.createElement("li");
list.innerHTML="JavaScript";
document
.getElementById("subjects")
.appendChild(list);
JavaScript
DOM allows developers to create table rows and cells dynamically based on data.
let row =
document.createElement("tr");
let cell =
document.createElement("td");
cell.innerHTML="HTML";
row.appendChild(cell);
This technique is commonly used for displaying database records and API data.
JavaScript can change images dynamically by modifying image attributes.
let image =
document.getElementById("photo");
image.src="new-image.jpg";
let img =
document.createElement("img");
img.src="picture.jpg";
document.body.appendChild(img);
JavaScript DOM can be used to create simple animations by changing element styles repeatedly.
Animations are used for sliders, moving objects, effects, and interactive components.
let box =
document.getElementById("box");
let position = 0;
function move()
{
position++;
box.style.left =
position+"px";
}
setInterval(move,10);
Adding and removing classes allows developers to create animations and interactive designs easily.
button.onclick=function()
{
box.classList.add("active");
}
JavaScript can create dynamic messages and notifications using DOM elements.
let message =
document.createElement("div");
message.innerHTML =
"Welcome User";
document.body.appendChild(message);
DOM concepts are used to create many real-world applications.
| HTML | DOM |
|---|---|
| Creates webpage structure. | Represents webpage as objects. |
| Static document. | Dynamic programming model. |
| Cannot change automatically. | Can modify content using JavaScript. |
| Written by developers. | Created by browser automatically. |
DOM Manipulation is a powerful JavaScript feature that allows developers to control and update webpage elements dynamically. Through the Document Object Model, JavaScript can access HTML elements, modify content, change styles, create new elements, remove elements, and handle user interactions.
Important DOM concepts include selecting elements, changing HTML content, modifying attributes, working with CSS classes, creating dynamic elements, form handling, and event-based updates.
A strong understanding of DOM manipulation is essential for developing interactive websites, modern web applications, dashboards, and user-friendly interfaces.