Removing Elements from the DOM

Learn how to remove and replace HTML elements with JavaScript.

Just as you can add elements, you can also remove and replace them dynamically.

remove() — Modern Method

let element = document.querySelector(".old-banner");
element.remove();  // Gone! Simple as that.

removeChild() — Classic Method

let parent = document.querySelector(".container");
let child = document.querySelector(".remove-me");

parent.removeChild(child);

Replacing Elements

// Create replacement
let newHeading = document.createElement("h2");
newHeading.textContent = "Updated Title";

// Replace old with new
let oldHeading = document.querySelector("h1");
oldHeading.replaceWith(newHeading);

// Classic way
let parent = oldHeading.parentElement;
parent.replaceChild(newHeading, oldHeading);

Clearing All Children

let container = document.querySelector(".container");

// Method 1: Set innerHTML to empty
container.innerHTML = "";

// Method 2: Remove children one by one
while (container.firstChild) {
    container.removeChild(container.firstChild);
}

// Method 3: replaceChildren with nothing
container.replaceChildren();

Practical Example — Remove List Items on Click

let list = document.querySelector("ul");

list.addEventListener("click", function(e) {
    if (e.target.tagName === "LI") {
        e.target.remove();
        console.log("Item removed!");
    }
});

Hiding vs Removing

// Hide (still in DOM, just invisible)
element.style.display = "none";

// Remove (completely gone from DOM)
element.remove();