12

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?

4 Answers 4

26

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); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, thanks to this, I can bind events on my Angular generated elements
3

The jQuery live() function does this:

$("#btn-remove-item").live('click', function() { this.parentNode.removeChild(this); }); 

2 Comments

live is deprecated, how can I achieve it through on?
you can use 'on', just select via document and use the selector argument of 'on' to get the right element. e.g. $(document).on( 'click', '#someThingCreatedLater', function (event) { ... do stuff ...});
1

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/

1 Comment

live() is deprecated now. Use on(). See this answer: stackoverflow.com/a/8191450/1738090
-1
$(document).ready(function(){ $(".btn-remove-item").live('click', function() { this.parentNode.removeChild(this); }); }); 

You are need to use live.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.