Module 34 : Creating and Removing Elements.
🧠 Prerequisite Knowledge
Basic HTML structure (tags, elements, attributes).
Introduction to the DOM and JavaScript selectors (getElementById, querySelector, etc.).
JavaScript functions and event handling.
1. Introduction to DOM Manipulation
DOM (Document Object Model) is a tree-like structure that represents the HTML document. JavaScript allows us to dynamically change, add, or delete elements in the DOM, making web pages interactive.
Use Cases:
Creating todo list items.
Dynamically loading content.
Form field additions.
Deleting messages, alerts, or UI components.
2. Creating Elements in JavaScript
✅ Syntax
javascript code
let newElement = document.createElement("tagName");
Example: Creating a New Paragraph
javascript code
let para = document.createElement("p"); para.textContent = "This is a new paragraph."; document.body.appendChild(para);
🧠 Explanation:
createElement("p"): Creates a new <p> tag in memory (not yet visible).
textContent: Adds text inside the tag.
appendChild(): Appends the element to the end of the body.
3. Adding Attributes, Classes, and IDs
javascript code
let div = document.createElement("div"); div.id = "newDiv"; div.className = "highlight-box"; div.setAttribute("data-role", "custom"); div.textContent = "This is a div with attributes."; document.body.appendChild(div);
🎓 Tip:
Explain the difference between:
element.id = "value" vs element.setAttribute("id", "value")
textContent vs innerHTML
4. Inserting Elements at Specific Positions
Use:
appendChild(): Adds to the end.
prepend(): Adds at the beginning.
insertBefore(newElement, existingElement)
after() / before() (modern, more readable)
Example:
javascript code
let newHeading = document.createElement("h2"); newHeading.textContent = "Inserted Heading"; let referenceNode = document.getElementById("mainTitle"); referenceNode.before(newHeading); // inserts before mainTitle
5. Removing Elements from the DOM
✅ Method 1: removeChild()
javascript code
let parent = document.getElementById("parentDiv"); let child = document.getElementById("childDiv"); parent.removeChild(child);
✅ Method 2: element.remove() (modern way)
javascript code
document.getElementById("childDiv").remove();
Note: remove() is not supported in very old browsers (pre-IE11).
6. Replacing Elements
javascript code
let newItem = document.createElement("li"); newItem.textContent = "New List Item"; let oldItem = document.getElementById("oldItem"); oldItem.parentNode.replaceChild(newItem, oldItem);
Exercise 1: Dynamic List Builder
Task:
Create a list of items using a button click.
🧱 HTML
html code
<button id="addBtn">Add Item</button> <ul id="itemList"></ul>
💻 JavaScript
javascript code
document.getElementById("addBtn").addEventListener("click", function () { let newItem = document.createElement("li"); newItem.textContent = "New Item " + Math.floor(Math.random() * 100); document.getElementById("itemList").appendChild(newItem); });
Exercise 2: Remove List Item on Click
javascript code
document.getElementById("itemList").addEventListener("click", function (e) { if (e.target.tagName === "LI") { e.target.remove(); } });
Use event delegation to target dynamically created elements.
Research: How Browsers Handle DOM Creation
JavaScript's createElement() constructs an in-memory node (not yet rendered).
It becomes part of the live DOM tree only after you insert it using appendChild(), insertBefore(), or similar methods.
These operations are CPU-intensive for large DOM trees—hence, developers often use DocumentFragment for batch updates to minimize reflows and repaints.
Advanced Techniques
📌 Using DocumentFragment
javascript code
let fragment = document.createDocumentFragment(); for (let i = 0; i < 5; i++) { let li = document.createElement("li"); li.textContent = "Item " + i; fragment.appendChild(li); } document.getElementById("itemList").appendChild(fragment);
✅ Why Use It?
Efficient DOM manipulation.
Reduces browser repaint and reflow events.
Ideal for inserting many nodes at once.
Structure
⏱️ Duration: 90 minutes
Time
Topic
10 min
Introduction to DOM and use cases
20 min
Creating elements and inserting them
15 min
Modifying attributes and styles
15 min
Removing and replacing elements
10 min
Optimizing with DocumentFragment
20 min
Live coding and student lab activities
📚 Additional References
MDN Web Docs:
createElement()
appendChild()
remove()
W3C Specification on DOM:
https://www.w3.org/TR/dom/
JavaScript.info:
https://javascript.info/modifying-document
Summary
createElement creates new nodes.
appendChild/prepend/insertBefore/after/before are used to place elements in the DOM.
remove() and removeChild() handle deletion.
DocumentFragment is useful for optimizing performance.
These techniques are crucial for building interactive UIs and single-page applications.
✅ Assignment
Create a dynamic todo list application that:
Adds new using a button.
Allows tasks to be removed by clicking on them.
Shows a counter of total tasks.
(Bonus) Persists tasks using localStorage.
No comments:
Post a Comment