JavaScript Reference ยท DOM: Document and Elements
Element.remove()
Reference for Element.remove(): take an element out of the DOM, keep a reference to reinsert it, and learn what happens to listeners, children and lookups.
remove() takes an element out of its parent. The page no longer shows it, and it no longer appears in the DOM tree. If the element has no parent, the call does nothing.
Removing does not destroy the element object. As long as you keep a variable pointing to it, you can insert it again later, and it keeps its children, attributes and event listeners.
document.querySelector(".banner")?.remove();
Try it
Syntax
element.remove()
Parameters: none.
Return value: undefined.
Exceptions: none. Calling it on an element without a parent is allowed and has no effect.
Usage notes
- Reference survives. Store the element in a variable before removing it if you may need it again. Re-inserting puts it back with its state, including listeners added with
addEventListener(). - Memory. When nothing references the element any more (no variables, no listeners from living objects), the engine can free it. Remove listeners for global targets such as
windowwhen a component goes away. - Children go along. The whole subtree is removed with the element.
- Removed from lookups.
getElementById()andquerySelector()no longer find it, and collections obtained earlier from live APIs update; a staticNodeListyou already hold does not. - Safe in a loop over a snapshot. Looping over
querySelectorAll()and callingremove()works, because the list is static. Looping over a livechildrencollection and removing as you go skips items. - Removing every child. Use
replaceChildren()with no arguments, orelement.textContent = "", rather than looping. - Older equivalent.
element.parentNode.removeChild(element)does the same but throws if the element is not a child of that parent. - Use
hiddenor a class when you only want to hide something temporarily; the element stays in the layout tree and keeps its state. - Other node types.
remove()is aChildNodemethod, so text and comment nodes have it too.
Browser support
Supported by all current browsers. Very old browsers only provide removeChild().