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();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
    <li>Notebook <button class="delete">Delete</button></li>
    <li>Jello <button class="delete">Delete</button></li>
    <li>Spinach <button class="delete">Delete</button></li>
    <li>Rice <button class="delete">Delete</button></li>
    <li>Birthday Cake <button class="delete">Delete</button></li>
    <li>Candles <button class="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 buttons
let deleteBtn = document.getElementsByClassName("btn");
// converting html collection to array, to use array methods
Array.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>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
  <li>Notebook <button class="btn" id="delete">Delete</button></li>
  <li>Jello <button class="btn">Delete</button></li>
  <li>Spinach <button class="btn">Delete</button></li>
  <li>Rice <button class="btn">Delete</button></li>
  <li>Birthday Cake <button class="btn">Delete</button></li>
  <li>Candles <button class="btn">Delete</button></li>
</ul>

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