Reputation: 26771
How do I bind events to html elements that don't exist at the time of the script loading?
One part of my script adds these to the DOM:
<a class="btn-remove-item" href="">link</a>
The problem is I can't just do:
$(document).ready(function(){
$(".btn-remove-item").click(function(){
this.parentNode.removeChild(this);
});
});
.. I think because the DOM element isn't there when the page first loads.
How should I bind the event to myClass?
Upvotes: 12
Views: 9659
Reputation: 1397
$(document).ready(function(){
$(".btn-remove-item").live('click', function() {
this.parentNode.removeChild(this);
});
});
You are need to use live.
Upvotes: -1
Reputation: 1179
jQuery.live() has been deprecated. Here is the accepted answer using jQuery.on() instead:
$(document).on('click', '#btn-remove-item', function() {
this.parentNode.removeChild(this);
});
Upvotes: 26
Reputation: 22210
jQuery.live() is what you need.
$(document).ready(function(){
$("a.myClass").live('click', function() {
this.parentNode.removeChild(this);
});
});
Try it out: http://jsfiddle.net/mwR8g/
Upvotes: 1
Reputation: 23774
The jQuery live() function does this:
$("#btn-remove-item").live('click', function() {
this.parentNode.removeChild(this);
});
Upvotes: 3