Skip to content
Related Articles

Related Articles

How to prepend list-item using jQuery with close event ?
  • Last Updated : 15 Oct, 2020
GeeksforGeeks - Summer Carnival Banner

Introduction: The task is to prepend list-item using jQuery. Items can be dynamically added and removed from a list using jQuery. This can be done by using event handlers to listen to button clicks. We will understand this with the help of an example.

Example:




<!DOCTYPE html>
<html>
  
<head>
    <style>
        li {
            list-style: none;
            margin: 1%;
        }
    </style>
  
    <script src=
    </script>
</head>
  
<body>
  
    <h1>List</h1>
    <ul id="list">
  
        <!-- List item with close button -->
        <li> <input type="text">
            <button class="close"> X</button>
        </li>
    </ul><br>
  
    <!-- Button to prepend list item -->
    <button class="add">+ Add item</button>
  
    <script>
  
        // When add button is clicked, 
        // list item is prepended
        $(".add").click(function () {
            $("#list").prepend(
'<li><input type = "text"><button class="close">X</button></li>');
        });
  
        // When close button is clicked, 
        // list item is removed
        $(document).on("click", 
            "button.close", function () {
                $(this).parent().remove();
            });
    </script>
</body>
  
</html>

Explanation: Here we have a list (id = “list”) with a text box and a close button (class = “close”). The button is used to remove an item from the list. At the end of list, we have an add button (class= “add”), used add a new list item at the beginning. 

$(".add").click(function () {
    $("#list").prepend('<li>
    <input type="text"> 
    <button class="close"> 
        X
    </button></li>');
});

.click() is added to the “add” button to listen to mouse clicks. When the button is clicked, a list item is added with a text box and a close button (having the same “close” class) using prepend() function. We have used the prepend function because we wanted to add an item at the beginning of the list. In order to add an item at the end, append() will be used.

$(document).on("click", "button.close", function () {
    $(this).parent().remove();
});

Here we have used on() function to listen to mouse clicks as click() doesn’t work with dynamically generated elements. Now it will also work for newly added “close” button. When the button with descendant class “close” is clicked, its parent (<li>, list item) is removed.



    Output:

  • Original list
  • After clicking on add button

    After clicking on add item, a new list item is prepended at the beginning of list

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :