Vanilla JavaScript Removing an Element


Extending our Drag n Drop editor with a remove function

18 May, 2020 · 2 min read

Yesterday we started building a Vanilla JavaScript Drag 'n Drop editor. We just couldn't remove the elements we added, so let's look into adding a remove button and the function to remove an element.

We don't need to make HTML changes, so let's get started on the CSS first.

CSS Changes

.comp-remove {
  position: absolute;
  color: red;
  top: calc(50% - 12px);
  right: 15px;
  font-weight: bold;
  cursor: pointer;
  pointer-events: all;

We will add a div with the class comp-remove, which is the styling. It will sit on the right side of the component and be centered vertically.

Vanilla JavaScript Remove Element

Inside our onDrop function, we are going to add the following after we define our const clone:

const clone = draggableElement.cloneNode(true);

// New
const remove = document.createElement('div');
remove.innerHTML = 'X';

Then at the bottom, we will add the function that will go off once we click this new element.

  function (event) {
    // If the clicked element doesn't have the right selector, bail
    if (!'.comp-remove')) return;
    // Don't follow the link
    // Get the parent element
    const parent =;
    // Delete the actual table parent;

We saw this way of adding a eventListener, and we listen to the specific comp-remove element. Then we get the parent element and that parent again (this is the dropzone element). We then say it should removeChild off the component.

You can try this out on this Codepen.

See the Pen Vanilla JavaScript Drag 'n Drop - Delete by Chris Bongers (@rebelchris) on CodePen.

Or see if on GitHub.

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2101 devs and subscribe to my newsletter