How to remove an element from the DOM?
There are several ways to remove an element from the DOM: from the classic (removeChild) to the modern (remove). Here are all the main options:
1. Modern way - .remove()
The simplest and most convenient.
javascript
const element = document.querySelector('.card');
element.remove(); // fully removes the element from the DOMThis method does not require reaching for the parent, it removes itself.
2. Classic way - parentNode.removeChild()
Used before .remove() appeared and still found in older code.
javascript
const element = document.querySelector('.card');
element.parentNode.removeChild(element);Usually needed if you have to support older browsers.
3. Removing all child elements
If you need to clear a container:
javascript
const container = document.querySelector('.list');
container.innerHTML = ''; // clears all contentor more explicitly:
javascript
while (container.firstChild) {
container.removeChild(container.firstChild);
}4. Conditional removal
You can, for example, remove an element on a click:
javascript
document.querySelector('.btn').addEventListener('click', () => {
const card = document.querySelector('.card');
card?.remove();
});5. Removing a specific node from a found set
javascript
document.querySelectorAll('.item').forEach((el, i) => {
if (i > 2) el.remove(); // remove all elements after the third
});Summary
| Way | When to use |
|---|---|
element.remove() | Modern and simple way |
parentNode.removeChild() | For old code and IE |
container.innerHTML = '' | Quickly clear a container |
| Conditional removal | For dynamic UI (on clicks, filters, etc.) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.