Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding events to not yet created DOM elements (jquery)

Tags:

html

jquery

dom

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?

like image 940
bgcode Avatar asked Aug 02 '10 21:08

bgcode


People also ask

Which method is used to bind a callback method for an event for DOM elements added at runtime?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event. Save this answer.

What method can you use to bind an event to an element?

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.

How do I grab an element from a DOM?

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.

What is bind event in jQuery?

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).


1 Answers

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);
});
like image 163
circuitry Avatar answered Sep 28 '22 20:09

circuitry