Remove li from ul

In last post we discussed about adding li to ul dynamically using jQuery. Now in this post we can see what are the possible ways to remove the li from ul. Below is the sample HTML code.

<input type=”button” id=”AddLI” value=”Add List to UL” />

<input type=”button” id=”remove-all” value=”Remove All” />

<input type=”button” id=”remove” value=”Remove except First and Second” />

<input type=”button” id=”remove2″ value=”Remove Only First and Second” />

<ul id=”ul-sample”>

</ul>

In the above code we have four buttons which can add li dynamically, remove all li from ul, remove all li except first and last child and remove only first and last child.

Remove All LI from the UL:-

If we want to remove all the li from a particular ul, then there is two ways to achieve that. First one is to remove all the li through below code

//Removing All li from ul
    $(‘#remove-all’).click(function () {

        $(‘ul#ul-sample’).empty(); // Method 1 Make ul empty

        $(‘ul#ul-sample li’).remove(); // Method 2 Removes All li

    });

In the above code there are two methods to remove li. We can use either of these.

Second one is to remove all li by looping through all li. This method will be useful when we needs to remove only some particular li’s specifically. For example by checking li values or by elements present within li. Below is the code for that

 //Removing All li from ul
    $(‘#remove-all’).click(function () {

        $(‘ul#ul-sample li’).each(function () { // loops through all li
            $(this).remove(); // Remove li one by one
        });

    });

Remove All LI from the UL Except First and Last:-

//Removing All li from ul except first and last
    $(‘#remove’).click(function () {       

        $(‘ul#ul-sample li:not(:first):not(:last)’).remove();

    });

Remove Only First and Last li of ul:-

//Removing only first and last li from ul
    $(‘#remove2’).click(function () {

        $(‘ul#ul-sample > :last-child, ul#ul-sample > :first-child’).remove();

    });