π 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)