DEV Community

Alex Morton
Alex Morton

Posted on

The Weird Thing About Deleting Items from Lists in JavaScript

When we create any type of program that includes functionality for adding and deleting items from a list on an app's interface, we need to pay extra attention to the features we include to delete items.

Before learning how to delete items off of lists, in my mind it seemed as simple as telling that specific item to delete itself from the DOM and it would disappear. But this is so wrong, and it really doesn't make any sense if you really think about it and have some JS experience under your belt.

Essentially, we can't just tell an item to delete itself. Instead, the deletion needs to be the responsibility of another related item. So, what we actually need is the item's parent element to do the deleting. Once we have access to that parent element, we can use the removeChild method to do so.

In other words, it's impossible to delete the item itself in JS, so we need to move up from the element to the parent node and then insert that same element to be removed into the removeChild property. Here's an example of that as a method of an object:

    deleteListItem: function(selectorID) {

      document.getElementById(selectorID).parentNode
      .removeChild(document.getElementById(selectorID));
    }
Enter fullscreen mode Exit fullscreen mode

And here's that same example after a bit of cleaning up/prettifying:

    deleteListItem: function(selectorID) {

      var element = document.getElementById(selectorID);
      element.parentNode.removeChild(element);
    }
Enter fullscreen mode Exit fullscreen mode

The end.

This post was originally published on March 5, 2020 on my blog.

Top comments (2)

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

insert that same element to be removed into the removeChild property

I think the wording here could confuse some readers. removeChild is a function, not a property, and you're calling it with a reference to the child node that the DOM should remove.

Collapse
 
alexlsalt profile image
Alex Morton

This is a great catch! Thank you -- editing now.