Element. remove()
Removes an element from the document along with all of its content.
- Returns
undefined- Changes the original
- Yes
Example
#const notification = document.querySelector('#n1')
notification.remove()
console.log(document.querySelector('#n1'))
console.log(notification.isConnected)
console.log(document.querySelectorAll('#notifications li').length)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
#element.remove()More examples
#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()document.querySelectorAll('#lessons .done').forEach((item) => item.remove())
const lessons = document.querySelector('#lessons')
console.log(lessons.children.length)
console.log(lessons.textContent)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 aschildren. - 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
#- Element.append()Adds elements or text at the end of an element’s content.
- Element.replaceWith()Replaces an element in the document with other elements or text. The old element is removed from the page.
- document.createElement()Creates a new HTML element with the given tag name, ready to be inserted into the page.
- document.querySelectorAll()Returns a static list (NodeList) of every element that matches a CSS selector.
- Element.closest()Returns the nearest ancestor (or the element itself) matching a CSS selector, or null.
- Event.targetThe element on which an event actually occurred, for example the clicked button inside a list.
Spotted a mistake or missing an example? Write to us.