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?
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event. Save this answer.
jQuery bind() Method The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.
The jQuery bind() event is used to attach one or more event handlers for selected elements from a set of elements. It specifies a function to run when the event occurs. It is generally used together with other events of jQuery. Syntax: $(selector).
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With