The modern **element.remove()** method deletes an element directly, without needing a parent reference. The legacy **parentNode.removeChild(el)** required knowing the parent. Also useful: **innerHTML = ''** to remove all children (but slower), **replaceChildren()** (modern, replaces all children), or **textContent = ''** (even faster for text-only clearing).
1Understanding Deleting DOM Elements
The modern element.remove() method deletes an element directly, without needing a parent reference. The legacy parentNode.removeChild(el) required knowing the parent. Also useful: innerHTML = '' to remove all children (but slower), replaceChildren() (modern, replaces all children), or textContent = '' (even faster for text-only clearing).
element.remove() doesn't return anything useful. After removal, the element still exists in memory — JavaScript holds a reference. It's only garbage collected when no references remain.
// Modern: element removes itself
const notification = document.querySelector('.notification');
btn.addEventListener('click', () => {
notification.remove(); // gone!
});
// Legacy: parent removes child
const parent = document.getElementById('container');
const child = parent.querySelector('.item');
parent.removeChild(child);2Practical Example
Here is a real-world application of Deleting DOM Elements showing how it is used in production JavaScript code.
// Remove all children
const list = document.querySelector('#list');
// Most efficient: replaceChildren
list.replaceChildren(); // clears all children
// Alternative: innerHTML = '' (triggers HTML parsing, slower)
list.innerHTML = ''; // slower but widely known3Best Practices
Follow these guidelines when working with Deleting DOM Elements:
1. Use element.remove() as the modern standard
2. Use replaceChildren() to clear all children efficiently
3. Null out references after removing for GC
Tip: element.remove() doesn't return anything useful. After removal, the element still exists in memory — JavaScript holds a reference. It's only garbage collected when no references remain.
// Modern: element removes itself
const notification = document.querySelector('.notification');
btn.addEventListener('click', () => {
notification.remove(); // gone!
});
// Legacy: parent removes child
const parent = document.getElementById('container');
const child = parent.querySelector('.item');
parent.removeChild(child);