Lesson 44 - Adding and Removing Elements in the DOM
Manipulating the DOM dynamically is essential for creating interactive web applications. JavaScript allows us to add and remove elements from the DOM using different methods.
Adding Elements to the DOM
You can add new elements to the DOM using:
document.createElement()
appendChild()
append()
prepend()
insertBefore()
Example 1: Creating and Appending a New Element
// Create a new paragraph element
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph added dynamically!";
// Append it to the body
document.body.appendChild(newParagraph);
createElement()
creates an element, andappendChild()
adds it to the page.
Removing Elements from the DOM
You can remove elements using:
removeChild()
remove()
Example 2: Removing an Existing Element
// Select an element
let paragraph = document.querySelector("p");
// Remove the selected element
paragraph.remove();
- The
remove()
method directly deletes the element.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson44-dom-manipulation.html
.
- Name it
-
Write the Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 44 - DOM Manipulation</title> </head> <body> <h2>Adding and Removing Elements</h2> <button id="add-btn">Add Paragraph</button> <button id="remove-btn">Remove Paragraph</button> <div id="container"></div> <script> let container = document.getElementById("container"); document.getElementById("add-btn").addEventListener("click", function() { let newP = document.createElement("p"); newP.textContent = "New paragraph added!"; container.appendChild(newP); }); document.getElementById("remove-btn").addEventListener("click", function() { let paragraphs = document.querySelectorAll("#container p"); if (paragraphs.length > 0) { paragraphs[paragraphs.length - 1].remove(); } }); </script> </body> </html>
-
Save the File.
-
Open it in a Browser and Click the Buttons.
Key Takeaways
createElement()
is used to create new elements dynamically.appendChild()
adds an element to the DOM.remove()
deletes an element from the DOM.- JavaScript allows adding and removing elements efficiently.