Removing Elements from the DOM
You'll learn how to delete elements from the webpage using two methods and understand the parent-child relationships that make removal possible.
When you need to remove an element from the page—maybe a notification dismisses, a list item gets deleted, or a modal closes—you're modifying the DOM tree by cutting out a branch. There are two main ways to do this, each with different requirements.
The removeChild() Method
The traditional approach requires you to access the parent element first, then remove its child:
const list = document.getElementById('myList');
const item = document.getElementById('item3');
list.removeChild(item); // Parent removes its child
Think of it like a tree: you can't just pluck a branch from thin air—you need to grab the trunk (parent) and remove the branch (child) from it.
You can also navigate to the parent from the child:
const item = document.getElementById('item3');
item.parentNode.removeChild(item); // Access parent, then remove child
The Modern remove() Method
The simpler, more intuitive method lets elements remove themselves:
const item = document.getElementById('item3');
item.remove(); // Element removes itself
No parent needed! The element simply disappears from the DOM tree.
Understanding the Relationship
With removeChild(), you must have the parent-child relationship clear: the parent calls the method and passes the child as an argument. With remove(), the element acts on itself. Both methods permanently remove the element from the DOM (though it still exists in memory if you stored it in a variable).
Key Takeaway: Use removeChild() when working with parent-child relationships explicitly, or use the modern remove() method for simpler, self-directed element removal—both permanently delete elements from the visible DOM tree.