Search code examples
javascripthtmlcsslistappendchild

Javascript deleting elements from a list


I hope someone can help me with my problem here. I've got a function which basically creates a list with user given inputs. For example: The user gives the input apples and the function adds apples to a <ul> list.

Now I have a question regarding deleting the inputs. For example: I want to delete the apples child from the list. This should happen in an input field when the user types in apples.

How can I do this?


Solution

  • You can use jQuery and remove the item from the list by running on the list with each() and remove it with remove(), here is an example:

    $( "button" ).click(function() { 
      var value = $('input').val() 
    
      $('ul li').each(function(index, li) {
        var item = $(li); 
        if(item.text() == value){
            item.remove()
        }
    
      }); 
    }); 
    

    you can check it on: https://jsfiddle.net/pww9uea8/

    you can check more about each() and remove() from jQuery documentation.