Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
document.querySelector(".banner")?.remove();

Try it

Remove on click
Removed does not mean gone

Syntax

JavaScript
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 window when a component goes away.
  • Children go along. The whole subtree is removed with the element.
  • Removed from lookups. getElementById() and querySelector() no longer find it, and collections obtained earlier from live APIs update; a static NodeList you already hold does not.
  • Safe in a loop over a snapshot. Looping over querySelectorAll() and calling remove() works, because the list is static. Looping over a live children collection and removing as you go skips items.
  • Removing every child. Use replaceChildren() with no arguments, or element.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 hidden or 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 a ChildNode method, so text and comment nodes have it too.

Browser support

Supported by all current browsers. Very old browsers only provide removeChild().