JavaScriptDOM and events

Element.remove()

Removes an element from the document along with all of its content.

Returns
undefined
Changes the original
Yes
On this page

Example

#
JavaScript
const notification = document.querySelector('#n1')

notification.remove()

console.log(document.querySelector('#n1'))
console.log(notification.isConnected)
console.log(document.querySelectorAll('#notifications li').length)
Console
null
false
1

Definition and usage

#

The remove() method detaches an element from the document, so it disappears from the page along with all of its children. You call it directly on the element you want to remove, without referring to its parent.

The removed element still exists in memory as long as you hold a reference to it in a variable. You can insert it back later, for example with append(). The isConnected property tells you whether the element is currently in the document.

The older way to do this is parent.removeChild(element). To remove all of an element’s children at once, the simplest approach is calling element.replaceChildren() with no arguments.

Syntax

#
Syntax
element.remove()

More examples

#
Removing after a click
JavaScript
const cart = document.querySelector('#cart')

cart.addEventListener('click', (event) => {
  if (!event.target.matches('.delete')) return
  event.target.closest('li').remove()
  console.log('Items in cart:', cart.children.length)
})

cart.querySelector('.delete').click()
Console
Items in cart: 1
Removing several elements
JavaScript
document.querySelectorAll('#lessons .done').forEach((item) => item.remove())

const lessons = document.querySelector('#lessons')
console.log(lessons.children.length)
console.log(lessons.textContent)
Console
1
Tags

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Removing elements from a querySelectorAll() list in a loop is safe, since that list is static. Watch out for “live” collections, though, such as children.
  • If the element should come back to the page, keep a reference to it in a variable and reinsert it with append().
  • To clear all of an element’s content, use element.replaceChildren().

Related entries

#

Spotted a mistake or missing an example? Write to us.