Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from div

Tags:

jquery

I wonder how do I always remove the last element of the div until there is only one element, the code follows below. I'm already able to do so later add it now is missing remove.

$("#add").click(function()
{
    $("#divparent").append($("#divchild").html());
});
$("#remove").click(function()
{
   //new code
});

<div id="divparent">
    <div id="divchild">
        <asp:DropDownList ID="DropDownList3" runat="server" Width="270"></asp:DropDownList>
    </div>
</div>
like image 659
Fernando Avatar asked Aug 23 '26 02:08

Fernando


2 Answers

First of all you don't want to give all the children the same id.

This should work for you:

$("#remove").click(function()
{
    $('#divparent').find(':last-child').not(':only-child').remove();
});

Working example: http://jsfiddle.net/AlienWebguy/Srfk2/

like image 132
AlienWebguy Avatar answered Aug 25 '26 17:08

AlienWebguy


I would do a few things.

  • I strongly advise you to not append an Item with the same ID as something else. Change it to a Class
  • if this is an asp based list and items are added dynamically you may want to look into .live()
  • I would clone() .divchild and not appened the child. Notice how I modified the add function
    • notice on .clone() that the default value is false, you may want to consider true, but should investigate this to fit your solution dependant on what is in your asp drop down list.

live example: http://jsfiddle.net/JWFu5/

$("#add").click(function() {
    $('.divchild:last').clone(true).fadeIn().insertAfter($('.divchild:last'));
});
$("#remove").click(function() {
    var count = $('.divchild').length;
    if (count > 1) {
        $('.divchild:last').fadeOut().detach()
    }
    else {
        alert('You Must Have At Least One Child');
    }
});
like image 45
matchew Avatar answered Aug 25 '26 17:08

matchew