Fernando
Fernando

Reputation: 75

Remove elements from div

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>

Upvotes: 3

Views: 10266

Answers (3)

SeanCannon
SeanCannon

Reputation: 77956

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/

Upvotes: 5

matchew
matchew

Reputation: 19645

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');
    }
});

Upvotes: 2

beardhatcode
beardhatcode

Reputation: 4753

$("#remove").click(function()
{
   if($('#divparent > div').length > 1){
          $('#divparent').find(':last-child').remove();
   }
});

to remove last till there is one left

Upvotes: 0

Related Questions