Featured
- Get link
- X
- Other Apps
🌿 Day 37 : JavaScript DOM Manipulation
🌿 Day 37 - JavaScript DOM Manipulation
Welcome to Day 37 of your JavaScript journey! 🎯 Today, we’ll dive into one of the most powerful and essential parts of JavaScript — DOM Manipulation. The Document Object Model (DOM) acts as a bridge between JavaScript and HTML, allowing developers to dynamically update, modify, or delete elements on a webpage in real time.
📘 What is the DOM?
The DOM is a tree-like structure that represents every element in your HTML document. Each tag, attribute, and text becomes a node in this structure that JavaScript can access and manipulate.
<!DOCTYPE html>
<html>
<body>
<h1>Hello DOM!</h1>
<p id="demo">This is a paragraph.</p>
</body>
</html>
🔍 Accessing Elements
JavaScript offers several methods to select and access DOM elements:
- document.getElementById("id") — Selects an element by its ID.
- document.getElementsByClassName("class") — Returns elements with a given class name.
- document.getElementsByTagName("tag") — Selects all elements of a given tag name.
- document.querySelector("selector") — Returns the first matching element.
- document.querySelectorAll("selector") — Returns all matching elements.
document.getElementById("demo").innerHTML = "Welcome to DOM Manipulation!";
🧱 Changing Content and Attributes
You can modify text, HTML, or attributes of elements using simple properties:
- innerHTML — Changes the inner HTML content.
- innerText — Changes only visible text.
- setAttribute() — Updates an element’s attribute.
- style.property — Dynamically changes CSS styles.
document.getElementById("demo").style.color = "blue";
document.getElementById("demo").setAttribute("class", "highlight");
✨ Creating and Removing Elements
The DOM allows you to dynamically create, append, and remove HTML elements.
let newPara = document.createElement("p");
newPara.innerText = "This paragraph was created with JavaScript!";
document.body.appendChild(newPara);
// To remove an element
let element = document.getElementById("demo");
element.remove();
🧠 Real-Life Example
Imagine building a shopping list where users can add or remove items dynamically — that’s DOM manipulation in action!
function addItem() {
let input = document.getElementById("itemInput").value;
let list = document.getElementById("shoppingList");
let newItem = document.createElement("li");
newItem.innerText = input;
list.appendChild(newItem);
}
💡 Summary
- The DOM connects JavaScript to your webpage.
- You can select, modify, create, and delete elements using DOM methods.
- Dynamic web applications rely heavily on DOM manipulation.
- Mastering this topic is key before moving on to events and form handling.
Popular Posts
📘 Day 36: Understanding the DOM (Document Object Model)
- Get link
- X
- Other Apps
Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
Comments
Post a Comment