Vanilla JavaScript Removing an Element

— 4 minute read

Yesterday we started building a Vanilla JavaScript Drag 'n Drop editor. We just weren't able to remove elements we added too much, 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 permalink

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

We are going to add a div with the class comp-remove so this is the styling, it's going to sit on the right side of the component and centered vertical.

Vanilla JavaScript Remove Element permalink

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 seen this way of adding a eventListener, and we listen to the specific comp-remove element. Then we get the parent element and the parent of that 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! permalink

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