Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic prepend and remove JQuery/JavaScript

I'm trying to dynamically add and remove items when I press the Append/Clear buttons in this piece of code.

                $("#btn1").click(function(){
                    $("ul").prepend("<li>List Item</li>");
                });

                $("#btn2").click(function(){
                     $("ul").remove();
                });

                 $("#btn3").click(function(){
                 $("p").prepend("Prepended items");
                     });
                $("#btn4").click(function(){
                      $("p").remove();
                     });

How do I make it so that when I press btn1 multiple times it will add a number after it like:

List Item 1
List Item 2
List Item 3

Then if I press btn2 it will remove them one by one? same goes for btn4?

EDIT:

I used Jai and Oday's answers to suit my needs.

var i = 1, p = 1;

        $("#btn1").click(function(){
            $('<li/>',{
                text: "List Item "+i
            }).appendTo('ul');
            i++;
        });

        $("#btn2").click(function(){
            $("ul li:last").fadeOut('fast').remove();
            i--; //added this
        });

        $("#btn3").click(function(){
            $("p").append("<span>Appended items</span>");
        });

        $("#btn4").click(function(){
            $("p").find('span:last').remove();
        });

2 Answers

Try with something like this:

var i = 1, p = 1;

$("#btn1").click(function(){
   $('<li/>',{
       text: "List Item "+i
   }).appendTo('ul');
   i++;
});

$("#btn2").click(function(){
   $("ul li:last").fadeOut('fast').remove();
});

$("#btn3").click(function(){
   $('<p/>',{
       text: "Prepended items "+p
   }).appendTo('ul');
   p++;
});

$("#btn4").click(function(){
   $("p").fadeOut('fast').remove();
});
like image 55
Jai Avatar answered Aug 03 '26 06:08

Jai


$("#btn1").click(function(){
    $("ul").append("<li>List Item</li>");
});

$("#btn2").click(function(){
    $("ul").find('li:last').remove();
});

$("#btn3").click(function(){
    $("p").append("<span>Appended items</span>");
});

$("#btn4").click(function(){
    $("p").find('span:last').remove();
});

Read more about jQuery functions: append, prepend, remove, empty, find,etc...

like image 45
Oday Fraiwan Avatar answered Aug 03 '26 06:08

Oday Fraiwan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!