DEV Community

Cover image for JavaScript remove elements
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

JavaScript remove elements

As we created new elements in JavaScript yesterday, I thought I'd be a good article for today to remove certain elements from the DOM.

To remove elements we simply need to get them in JavaScript using any technique really.

Let's say we want to remove a div with the ID custom_id.

const elem = document.getElementById('custom_id');
elem.remove();
Enter fullscreen mode Exit fullscreen mode

And yes, that's how simple it is!

Hiding elements in JavaScript

But perhaps you only want to hide it for a brief moment?
We can also modify the script to make the element invisible for a while.

const hidden = document.getElementById('hidden_id');
hidden.style.display = 'none';
Enter fullscreen mode Exit fullscreen mode

And that will make your element hidden until you make it visible again.

Making it visible can be achieved by swapping the display to block/flex/inline.

const hidden = document.getElementById('hidden_id');
hidden.style.display = 'block';
Enter fullscreen mode Exit fullscreen mode

Feel free to check this out on Codepen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (5)

Collapse
 
lexlohr profile image
Alex Lohr

element.remove() is a fairly recent addition to the DOM. Before that, we used parentNode.removeChild(element).

Collapse
 
daviddalbusco profile image
David Dal Busco

I also always use removeChild so far.

const elem = document.getElementById('custom_id');
elem.parentElement.removeChild(elem);
Enter fullscreen mode Exit fullscreen mode

Cool to know it will be possible in the future without referencing the parent, thanks for the post Chris ๐Ÿ‘

Collapse
 
dailydevtips1 profile image
Chris Bongers

Pretty nice addition, right?

Thread Thread
 
daviddalbusco profile image
David Dal Busco

Indeed, pretty cool ๐Ÿ‘

Collapse
 
dailydevtips1 profile image
Chris Bongers

Yeah such a welcome addition ๐Ÿคฉ