Ben G
Ben G

Reputation: 26771

Binding events to not yet created DOM elements (jquery)

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

Answers (4)

Ashisha Nautiyal
Ashisha Nautiyal

Reputation: 1397

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

You are need to use live.

Upvotes: -1

circuitry
circuitry

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

Bertrand Marron
Bertrand Marron

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

You
You

Reputation: 23774

The jQuery live() function does this:

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

Upvotes: 3

Related Questions