Module 31 : Manipulating Elements
1. Introduction to the DOM (Document Object Model)
The DOM is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content.
According to the Mozilla Developer Network (MDN), the DOM is structured as a tree of nodes, and every element, attribute, and piece of text becomes a node.
2. Selecting Elements
Methods to Select Elements:
Method
Description
getElementById()
Selects a single element by its ID
getElementsByClassName()
Selects all elements with a specific class name
getElementsByTagName()
Selects all elements with a specific tag name
querySelector()
Returns the first element that matches a CSS selector
querySelectorAll()
Returns all elements matching a CSS selector
Example:
html code
<div id="message" class="box">Hello</div>
javascript code
const messageBox = document.getElementById("message"); console.log(messageBox.textContent); // Outputs: Hello
3. Changing Content and Attributes
Changing Text or HTML:
javascript code
messageBox.textContent = "Updated Message"; // Plain text messageBox.innerHTML = "<b>Updated Message</b>"; // HTML
Changing Attributes:
javascript code
messageBox.setAttribute("class", "new-class"); messageBox.getAttribute("id"); // Returns "message" messageBox.removeAttribute("class");
4. Manipulating CSS Styles
javascript code
messageBox.style.color = "red"; messageBox.style.backgroundColor = "yellow"; messageBox.style.fontSize = "20px";
You can also use classList to add or remove classes:
javascript code
messageBox.classList.add("highlight"); messageBox.classList.remove("box"); messageBox.classList.toggle("active");
5. Creating and Adding Elements
Create an Element and Append:
javascript code
const newDiv = document.createElement("div"); newDiv.textContent = "I am a new div!"; document.body.appendChild(newDiv);
You can also insert elements in specific locations using:
appendChild()
insertBefore()
replaceChild()
6. Removing Elements
javascript code
const oldElement = document.getElementById("message"); oldElement.remove(); // Removes the element from the DOM
Or:
javascript code
oldElement.parentNode.removeChild(oldElement);
7. Event-Based Manipulation
Add interactivity by manipulating elements in response to events.
html code
<button id="changeBtn">Change Text</button> <p id="text">Original Text</p>
javascript code
document.getElementById("changeBtn").addEventListener("click", function() { document.getElementById("text").textContent = "Text Changed!"; });
8. Toggle Visibility
html code
<button onclick="toggleVisibility()">Toggle</button> <div id="box">Toggle Me!</div>
javascript code
function toggleVisibility() { const box = document.getElementById("box"); if (box.style.display === "none") { box.style.display = "block"; } else { box.style.display = "none"; } }
9. Title : Build a Dynamic List Editor
Objective:
Practice creating, adding, and deleting elements using DOM manipulation.
Setup:
html code
<input type="text" id="itemInput" placeholder="Add item"> <button onclick="addItem()">Add Item</button> <ul id="itemList"></ul>
JavaScript:
javascript code
function addItem() { const input = document.getElementById("itemInput"); const list = document.getElementById("itemList"); if (input.value !== "") { const li = document.createElement("li"); li.textContent = input.value; // Add remove button const btn = document.createElement("button"); btn.textContent = "Remove"; btn.onclick = () => li.remove(); li.appendChild(btn); list.appendChild(li); input.value = ""; // Clear input } }
Expected Outcome:
User enters an item → clicks "Add Item" → item appears in list with a "Remove" button.
10. Exercise
Exercise 1:
Change the background color of an element with ID box to blue when a button is clicked.
Solution:
javascript code
document.getElementById("myButton").addEventListener("click", function() { document.getElementById("box").style.backgroundColor = "blue"; });
Exercise 2:
Create a paragraph element with your name and add it to the body.
Solution:
javascript code
const para = document.createElement("p"); para.textContent = "Syeda Rehana"; document.body.appendChild(para);
Exercise 3:
Toggle a class called "highlight" on a div with the ID toggleDiv.
Solution:
javascript code
document.getElementById("toggleBtn").addEventListener("click", function() { document.getElementById("toggleDiv").classList.toggle("highlight"); });
11. Research Insights
1. Performance Consideration:
Frequent DOM manipulation can slow down rendering. Use DocumentFragments to batch changes.
2. Separation of Concerns:
Avoid mixing inline JavaScript (onclick) and HTML. Prefer addEventListener.
3. Accessibility:
Ensure manipulated elements remain accessible (e.g., maintain keyboard navigation, aria attributes).
4. Security:
Avoid using innerHTML with user input to prevent XSS attacks.
12. Summary
The DOM allows dynamic interaction with your webpage.
Use selection methods (getElementById, querySelector) to target elements.
Modify content, style, classes, and attributes using JavaScript.
Add interactivity using event listeners.
Build dynamic user interfaces with create, insert, and remove functions.
13. Interactive Todo List
Create a form to input tasks.
Display tasks in a list.
Each task should have a delete and complete button.
Use DOM methods only (no libraries).
No comments:
Post a Comment