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.classList.add('comp-remove');
remove.innerHTML = 'X';
clone.appendChild(remove);

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

document.addEventListener(
  'click',
  function (event) {
    // If the clicked element doesn't have the right selector, bail
    if (!event.target.matches('.comp-remove')) return;
    // Don't follow the link
    event.preventDefault();
    // Get the parent element
    const parent = event.target.parentNode;
    // Delete the actual table parent;
    parent.parentNode.removeChild(parent);
  },
  false
);

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 ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API