JavaScript: remove()
The Element.remove() method removes an element from the document.
What you will learn
- How to select an element to remove
- How remove changes the document
- How to avoid errors when the target does not exist
Minimal example
<ul id="list">
<li id="remove-me">Remove this item</li>
</ul>const item = document.querySelector('#remove-me');
if (item) item.remove();The selected li is removed from its parent list. The variable still refers to the removed node, but it is no longer connected to the document.
Common mistakes
- Check that the selector found an element before calling
remove(). - Removing an element also removes its descendants from the document.
- If you may need the element later, keep its data or create it again before removing it.