Spex3
    

JavaScript DOM Manipulation 🌐


    

    

JavaScript DOM Manipulation 🌐
The Document Object Model (DOM) allows JavaScript to interact with and modify an HTML document dynamically.

1️⃣ What is the DOM?
The DOM represents an HTML page as a tree-like structure, where:

HTML elements are nodes.

JavaScript can select, modify, and delete elements.

Example HTML Document:


<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<p class="info">Welcome to JavaScript DOM manipulation.</p>
<button id="btn">Click Me</button<
</body>
</html>


2️⃣ Selecting HTML Elements 📌
✅ 1. getElementById() – Selects an Element by ID
 
let title = document.getElementById("title");
console.log(title); //

Hello, World!




✅ 2. getElementsByClassName() – Selects Elements by Class (Returns a Collection)
 
let paragraphs = document.getElementsByClassName("info");
console.log(paragraphs[0]); //

Welcome to JavaScript DOM manipulation.




✅ 3. querySelector() – Selects the First Matching Element
 
let firstParagraph = document.querySelector(".info");
console.log(firstParagraph); //

Welcome to JavaScript DOM manipulation.




✅ 4. querySelectorAll() – Selects All Matching Elements (Returns a NodeList)
 
let allParagraphs = document.querySelectorAll(".info");
console.log(allParagraphs); // NodeList of matching elements


3️⃣ Modifying HTML Elements 🛠️
✅ 1. Changing Text Content
 
title.textContent = "Welcome to the DOM!";


✅ 2. Changing HTML Content (innerHTML)
 
firstParagraph.innerHTML = "<strong>DOM is powerful!</strong>";

✅ 3. Changing CSS Styles (style)
<
title.style.color = "blue";
title.style.fontSize = "30px";


4️⃣ Event Listeners 🎯
✅ 1. Adding an Event Listener (addEventListener)
<
let button = document.getElementById("btn");

button.addEventListener("click", function() {
alert("Button clicked!");
});


✅ 2. Changing Text on Button Click
 

button.addEventListener("click", function() {
title.textContent = "You clicked the button!";
});



5️⃣ Summary
✅ Use getElementById(), querySelector(), etc., to select elements.
✅ Modify text with textContent or innerHTML.
✅ Change styles using style.property.
✅ Handle user interactions with addEventListener()


    Date: 2025-03-29 00:00:00.000000