Search code examples
javascripthtml-listslistitem

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 their item that I chose without using their index.

let enterListBtn = document.getElementById("enter");
let input = document.getElementById("userinput");
let ul = document.querySelector("ul");
let togList = document.getElementsByTagName("li");
let deleteBtn = document.getElementById("delete");

function deleteItem() {
    togList.parentNode.removeChild(togList);
}

deleteBtn.addEventListener("click", deleteItem);

HTML

<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 id="delete">Delete</button></li>
    <li>Jello <button>Delete</button></li>
    <li>Spinach <button>Delete</button></li>
    <li>Rice <button>Delete</button></li>
    <li>Birthday Cake <button>Delete</button></li>
    <li>Candles <button>Delete</button></li>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>

Solution

  • 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>