Reputation: 25
With this code I'm able to add a div with some text and and hyperlink inside the div:
$('<div/>')
.html("<a href='#'>x</a> " + i.item.label + " - ")
.attr({ 'id': i.item.val })
.addClass('boxClass')
.appendTo('#acResults');
I'd like to remove the created link when I click on the x
link inside the created div. Something similar to the remove tag in the tags section of this site.
Could you please help me?
Upvotes: 1
Views: 65
Reputation: 28513
You can do this : add click event using .on()
(we do it for dynamically created element) and use .remove()
to remove clicked link.
$(document).on('click','div.boxClass a',function(){
$(this).remove();
});
EDIT - as OP mentioned "I'd like to remove the created link when I click on the x link inside the created div" in the post, but it looks like OP want to remove div
and not the link. Please find below updated answer -
$(document).on('click','div.boxClass a',function(){
$(this).closest('div.boxClass').remove();
});
Upvotes: 1
Reputation: 749
add some class to this link
$('<div/>')
.html("<a class='remove-link' href='#'>x</a> " + i.item.label + " - ")
.attr({'id': i.item.val})
.addClass('boxClass')
.appendTo('#acResults');
and then try
$('.remove-link').click(function (event) {
event.preventDefault();
$(this).remove();
});
Upvotes: 0
Reputation: 337560
Because the element is appended dynamically you would need to use a delegated event handler. From there you can use closest()
to find the parent div
and remove it. Try this:
$('#acResults').on('click', '.boxClass a', function(e) {
e.preventDefault();
$(this).closest('.boxClass').remove();
});
Upvotes: 2