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?

Ben G
  • 26,091
  • 34
  • 103
  • 170

4 Answers4

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);
});
circuitry
  • 1,169
  • 16
  • 16
3

The jQuery live() function does this:

$("#btn-remove-item").live('click', function() {
    this.parentNode.removeChild(this);
});
You
  • 22,800
  • 3
  • 51
  • 64
  • 1
    live is deprecated, how can I achieve it through `on`? – Juzer Ali Apr 23 '13 at 14:50
  • 2
    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 ...});` – tehfoo May 13 '13 at 22:27
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/

Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
  • 1
    `live()` is deprecated now. Use `on()`. See this answer: http://stackoverflow.com/a/8191450/1738090 – w3bshark May 15 '13 at 13:31
-1
$(document).ready(function(){
     $(".btn-remove-item").live('click', function() {
        this.parentNode.removeChild(this);
    });
});

You are need to use live.

Ashisha Nautiyal
  • 1,389
  • 2
  • 19
  • 39