Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

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:

  1. document.createElement()
  2. appendChild()
  3. append()
  4. prepend()
  5. 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, and appendChild() adds it to the page.

Removing Elements from the DOM

You can remove elements using:

  1. removeChild()
  2. 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:

  1. Create a File:

    • Name it lesson44-dom-manipulation.html.
  2. 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>
  3. Save the File.

  4. 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.