Remove an Element from the DOM on Click using JavaScript

avatar

Borislav Hadzhiev

Sun Jan 02 20222 min read

banner

Photo by Luke Braswell

Remove an Element from the DOM on Click using JavaScript #

To remove an element from the DOM on click:

  1. Select the DOM element.
  2. Add a click event listener to the element.
  3. Call the remove() method on the element in the event handler.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="background-color: salmon; width: 100px; height: 100px"> Box 1 </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); box.addEventListener('click', function handleClick(event) { box.remove(); });

We added a click event listener to the DOM element.

Each time the element is clicked, a function is invoked.

In our handler function, we used the Element.remove method to remove the element from the DOM.

We could have also used the target property on the event object to achieve the same result.

index.js
const box = document.getElementById('box'); box.addEventListener('click', function handleClick(event) { event.target.remove(); });

In the example above, we used the target property on the event object.

The target property is a reference to the object (element) on which the event was dispatched.

In other words event.target gives us access to the DOM element the user clicked.

You can console.log the target property to see the DOM element which was clicked by the user.

index.js
const box = document.getElementById('box'); box.addEventListener('click', function handleClick(event) { console.log(event.target); event.target.remove(); });

If you click on the div element and look at your browser's console, you'll see the element being logged.

The target property is very useful when adding events to more generic objects, e.g. the document.

Here is an example that removes the clicked DOM element, regardless of which element it is.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div style="background-color: salmon; width: 100px; height: 100px"> Box 1 </div> <div style=" background-color: salmon; width: 100px; height: 100px; margin-top: 10px; margin-bottom: 10px; " > Box 2 </div> <div style="background-color: salmon; width: 100px; height: 100px"> Box 3 </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
document.addEventListener('click', function handleClick(event) { console.log(event.target); event.target.remove(); });

This time we added the event to the document object.

Each time an element is clicked, we remove it from the DOM, regardless of which element it was.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee