๐ DOM Manipulation in JavaScript โ Step by Step Guide
If youโre learning JavaScript, DOM Manipulation is one of the most important skills you must understand.
In this article, weโll learn:
- What the DOM is
- How to select elements
- How to change content and styles
- How to handle events
- How to create and remove elements
Everything with simple examples ๐
๐ง What is the DOM?
DOM stands for Document Object Model.
When a web page loads, the browser converts HTML into a tree-like structure that JavaScript can access and modify.
JavaScript uses the DOM to read, change, add, or remove elements on a web page.
๐งฉ Sample HTML
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation</title>
</head>
<body>
<h1 id="title">Hello DOM</h1>
<p class="description">Learning DOM manipulation</p>
<button id="btn">Click Me</button>
<script src="script.js"></script>
</body>
</html>
๐ Step 1: Selecting DOM Elements
1๏ธโฃ Select by ID
const title = document.getElementById("title");
console.log(title);
2๏ธโฃ Select by Class
const desc = document.getElementsByClassName("description");
console.log(desc[0]);
3๏ธโฃ Select using CSS Selectors (Recommended)
const heading = document.querySelector("#title");
const paragraph = document.querySelector(".description");
โ๏ธ Step 2: Changing Text Content
You can change the text inside elements using textContent or innerHTML.
heading.textContent = "DOM is Awesome!";
heading.innerHTML = "<span>DOM is Powerful!</span>";
๐จ Step 3: Changing Styles
You can also change the style of elements dynamically.
heading.style.color = "blue";
heading.style.fontSize = "32px";
Or use CSS classes:
.highlight {
color: red;
background: yellow;
}
heading.classList.add("highlight");
๐ฑ๏ธ Step 4: Handling Events
You can respond to user actions like clicks.
const button = document.querySelector("#btn");
button.addEventListener("click", () => {
alert("Button clicked!");
heading.textContent = "You clicked the button!";
});
โ Step 5: Creating New Elements
Create and insert new elements into the DOM.
const newParagraph = document.createElement("p");
newParagraph.textContent = "This paragraph was created using JavaScript";
document.body.appendChild(newParagraph);
โ Step 6: Removing Elements
Remove elements from the DOM when needed.
newParagraph.remove();
๐ Step 7: Full Mini Example
Hereโs a full working example:
button.addEventListener("click", () => {
const item = document.createElement("li");
item.textContent = "New Item Added";
document.body.appendChild(item);
});
Top comments (0)