🌐 DOM Manipulation in JavaScript
DOM stands for Document Object Model.
It allows JavaScript to interact with HTML elements and dynamically change the content, structure, and styling of a webpage.
For example, JavaScript can:
• Change heading text.
• Change colors and styles.
• Add or remove HTML elements.
• Respond to button clicks.
• Validate form inputs.
• Make webpages interactive.
Let's understand it step by step.
1️⃣ What is the DOM?
When a browser loads an HTML page, it creates a tree-like structure of elements called the DOM.
Example HTML:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>Welcome to JavaScript</p>
</body>
</html>
JavaScript can access and modify these elements through the DOM.
2️⃣ Selecting HTML Elements
Before changing an element, we need to select it.
getElementById()Selects an element using its ID.
<h1 id="title">Hello World</h1>
let heading = document.getElementById("title");
console.log(heading);querySelector()Selects the first element matching a CSS selector.
let heading = document.querySelector("#title");
let paragraph = document.querySelector(".description");querySelectorAll()Selects all elements matching a CSS selector.
let items = document.querySelectorAll("p");
console.log(items);Other selection methods:
•
getElementsByClassName(), Selects elements by class name.•
getElementsByTagName(), Selects elements by tag name.3️⃣ Changing Text Content
JavaScript allows us to change the text inside HTML elements.
<h1 id="heading">Old Heading</h1>
let heading = document.getElementById("heading");
heading.textContent = "Welcome to JavaScript!";The heading will now display:
Welcome to JavaScript!textContent vs innerHTML•
textContent changes or retrieves text.•
innerHTML reads or changes HTML markup inside an element.Example:
document.getElementById("heading").innerHTML =
"<span>Hello JavaScript</span>";Use
innerHTML carefully with untrusted input because inserting unsafe HTML can create security vulnerabilities.4️⃣ Changing CSS Styles
You can dynamically change the styling of an element.
<p id="message">Hello World</p>
let message = document.getElementById("message");
message.style.color = "blue";
message.style.fontSize = "24px";
message.style.backgroundColor = "lightyellow";The paragraph's appearance will change instantly.
5️⃣ Adding and Removing CSS Classes
Instead of changing individual styles, you can use
classList.add()element.classList.add("active");remove()element.classList.remove("active");toggle()Adds a class if it doesn't exist and removes it if it does.
element.classList.toggle("active");contains()Checks whether an element has a particular class.
console.log(element.classList.contains("active"));