HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Remove an element from the DOM using JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
domjavascriptfromelementremovetheusing

Problem

DOM manipulation is one of the primary reasons JavaScript even exists. That being said, removing an element from the DOM is one of the most common tasks you'll encounter.
While it sounds simple, you can't simply ask an element to remove itself. Instead, you need to access its parent node and remove the element from there. To do so, you'll have to use the Node.parentNode property to get the parent node and then call Node.removeChild() to remove the element from the parent node.

Solution

const removeElement = el => el.parentNode.removeChild(el);

removeElement(document.querySelector('#my-element'));
// Removes #my-element from the DOM

Code Snippets

const removeElement = el => el.parentNode.removeChild(el);

removeElement(document.querySelector('#my-element'));
// Removes #my-element from the DOM

Context

From 30-seconds-of-code: remove-dom-element

Revisions (0)

No revisions yet.