Subscribe

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 馃摉

TypeORM viewEntity

30 Mar, 2022 路 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 路 3 min read

The Record Utility Type in TypeScript

Join 1513 devs and subscribe to my newsletter