Reputation: 2711
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
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
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
Reputation: 87073
.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.
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