tags:

views:

20

answers:

2

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?

+1  A: 

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
thank you very much
babonk
+2  A: 

The jQuery live() function does this:

$("#btn-remove-item").live('click', function() {
    this.parentNode.removeChild(this);
});
You
excellent, thank you much
babonk