Skip to content Skip to sidebar Skip to footer

Delete Specific List Item From Unordered List When Delete Button Is Clicked

I'm new in learning Javascript. I wanted to delete specific list item in my unordered list. Every item has a delete button, I just can't figure out how my buttons will know if it's

Solution 1:

simply add a class for every delete button, in the jquery add click event method, then get parent of button remove it.. check this code..

 $('.delete').on('click', function(){
      $(this).parent().remove();
    });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body><h1>Shopping List</h1><pid="first">Get it done today</p><inputid="userinput"type="text"placeholder="enter items"><buttonid="enter">Enter</button><ul><li>Notebook <buttonclass="delete">Delete</button></li><li>Jello <buttonclass="delete">Delete</button></li><li>Spinach <buttonclass="delete">Delete</button></li><li>Rice <buttonclass="delete">Delete</button></li><li>Birthday Cake <buttonclass="delete">Delete</button></li><li>Candles <buttonclass="delete">Delete</button></li></ul></body>

Solution 2:

You can target the element using the event object then use parentNode to delete the element

// adda common class to all the buttonslet deleteBtn = document.getElementsByClassName("btn");
// converting html collection to array, to use array methodsArray.prototype.slice.call(deleteBtn).forEach(function(item) {
  // iterate and add the event handler to it
  item.addEventListener("click", function(e) {
    e.target.parentNode.remove()
  });

})
<h1>Shopping List</h1><pid="first">Get it done today</p><inputid="userinput"type="text"placeholder="enter items"><buttonid="enter">Enter</button><ul><li>Notebook <buttonclass="btn"id="delete">Delete</button></li><li>Jello <buttonclass="btn">Delete</button></li><li>Spinach <buttonclass="btn">Delete</button></li><li>Rice <buttonclass="btn">Delete</button></li><li>Birthday Cake <buttonclass="btn">Delete</button></li><li>Candles <buttonclass="btn">Delete</button></li></ul>

Post a Comment for "Delete Specific List Item From Unordered List When Delete Button Is Clicked"