Removing Elements
Removing Elements
Section titled “Removing Elements”Introduction
Section titled “Introduction”Remove DOM elements cleanly using modern methods.
Removing an Element
Section titled “Removing an Element”const element = document.querySelector('.to-remove');
// Modern method (preferred)element.remove();
// Legacy methodelement.parentNode.removeChild(element);Removing Children
Section titled “Removing Children”const parent = document.querySelector('.container');
// Remove all childrenwhile (parent.firstChild) { parent.removeChild(parent.firstChild);}
// Modern: replace content (clears children)parent.replaceChildren();
// Or simply: innerHTML = '' (fast but unsafe with listeners)parent.innerHTML = '';Summary
Section titled “Summary”element.remove()— modern, clean removalelement.parentNode.removeChild(element)— legacy methodparent.replaceChildren()— removes all children- Always clean up event listeners when removing elements