Biker John
Biker John

Reputation: 2711

Append and remove element on click

Im trying to add and remove div with click. I succeeded in adding it but cant figure out the remove part.

HTML:

<center>
<a href='#' id='gogo'>Add</a>
<div id='sexy'></div>
</center>

jQuery:

var extra="<div class='bass'><a href='#' class='gaga'>Remove</a></div>";

$('#gogo').on('click', function(){


    $('#sexy').append(extra);



});

$('.gaga').on('click', function(){


    $(this).parent().remove();



});

JSFIDDLE: http://jsfiddle.net/Vmhe2/1/

Upvotes: 0

Views: 139

Answers (5)

OctoD
OctoD

Reputation: 361

http://jsfiddle.net/Vmhe2/49/

try this :)

Upvotes: 1

Vytalyi
Vytalyi

Reputation: 1695

This should help

$('#gogo').on('click', function(){

    $('#sexy').append(extra);

    $('.gaga').on('click', function() {
         $(this).parent().remove();
    });

});

I have moved remove function right after appending extra div

Upvotes: 2

Steven Hunt
Steven Hunt

Reputation: 2321

When you register the event handler, the DOM element has to exist at that moment. If you want it bound dynamically, use delegate(): http://api.jquery.com/delegate/

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

Yes, .remove() will completely remove the element from DOM tree.


But, your remove code should look like:

$('#sexy').on('click', '.gaga', function(e){ 
    e.preventDefault();  // as .gaga is anchor, so use preventDefault() 
                         // to stop default page load of browser
    $(this).parent().remove();
});

As you're appending .gaga dynamically so you need delegate event handling and you can do it using .on() method.

Working sample


Note

Syntax of .on() for delegate event (aka live) is:

$(StatciParent).on(eventName, target, handlerFunction);

Where, StaticParent refers to the parent of target element which is not dynamic and target is the element to which you need to bind the event.

Upvotes: 1

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5153

Yes, the element is completely removed from the DOM.

Upvotes: 1

Related Questions