Skip to content
Related Articles

Related Articles

How to prepend list-item using jQuery with close event ?

Improve Article
Save Article
  • Last Updated : 15 Oct, 2020
Improve Article
Save Article

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.


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

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 () {
    <input type="text"> 
    <button class="close"> 

.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 () {

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.


  • Original list
  • After clicking on add button

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!