JSFiddle - React, Tailwind, and code Playground

(Pure JS) Click to remove items from a list by manipulating the DOM / includes fall-back commands for older versions of IE

by Don Schaefer

HTML

<p>Click on a fruit to remove it from the list</p>
<ul id="toBuyList">
    <li><a href="#">Apples</a></li>
    <li><a href="#">Oranges</a></li>
    <li><a href="#">Bananas</a></li>
    <li><a href="#">Peaches</a></li>
    <li><a href="#">Plums</a></li>
</ul>

CSS

ul {
    background-color: #666;
    padding: 5px;
}
li {
    list-style-type: none;
    padding: 10px;
    background-color: #aaa;
    margin: 5px;
}
a {
    text-decoration: none;
    background-color: #ccc;
    color: #000;
    padding: 5px;
}

JavaScript

//First we need to create a function that will allow us to determine the target of the event. This is necessary because older versions of IE do not generate event objects & without them, we can't find the target of the event
function getTarget(e){
    //Find out whether or not an event object even exists yet
    if(!e){
        //If an event object doesn't exist, set it equal to the generic "window.event" object that older versions of IE DO support
        e = window.event;
    }
    //return the target of the event (or, if there is no "target" since older versions of IE don't recognize that, get the IE equivalent "srcElement")
    return e.target || e.srcElement;
}
        

//Next we need a function that will run if/when a user clicks on something
function itemPurchased(e){
    //Set up variables to identify relevant elements on the page
    var target = getTarget(e);
    var elParent = target.parentNode;
    var elGrandParent = elParent.parentNode;

    //verify that the user is clicking a link element with a textNode for a child rather than some other element on the pagething else (necessary since our listener is on the list rather than the individual list items or links)
    //element node = 1 / attribute node = 2 / text node =  3 / comment node = 8
    if(target.childNodes[0].nodeType === 3){
        //Remove the target element & it's associated parent element
        elGrandParent.removeChild(elParent);
    }
    
    //Check to see if the browser supports the "preventDefault" command
    if(e.preventDefault){
        //If it does, use the command to ensure that the associated link does not take you to another page
        e.preventDefault();
    }else{
        //If it doesn't, it's an older version of IE & we'll use an equivalent command instead
        e.returnValue = false;
    }
}

//Now that our functions are created, we'll create a variable to reference the parent element of the elements you'll be targeting (this will ensure that additional code does...