The correct method to call .each on dynamically created elements?

Following from the answer here is https://stackoverflow.com/a/169608/ and now the pretty old jQuery plugin ( http://www.erichynds.com/jquery/jquery-create-event/ )

What is the right event for on to catch when creating new elements? For example, I have input fields in which I set typeahead / autocomplete. I am doing this with:

 $(.input_box).each( function() { // set stuff here // setup options etc // apply autocomplete plugin to element (this is a jQuery plugin) var ac = $(this).autocomplete(acOptions); }); 

Then I have a button to add more identical input fields to the form. How can I call this .each function only for a new input field? If I use $(.input_box).each... , the source fields will add the plugin a second time.

Basically I want to do the following, but there is no reference to "creation".

 $(document).on("create", "input_box", function(e) { // set stuff here // setup options etc // apply autocomplete plugin to element (this is a jQuery plugin) var ac = $(this).autocomplete(acOptions); } ); 

Is there such an event? If not, what is the best way to achieve this?

+4
source share
1 answer

As mentioned above: you can use mutation events. But these events have some limitations: there is no support for IE prior to version 9, and there are some performance problems with these events. In your case, you should listen to DOMNodeInserted . Possible example:

 document.addEventListener("DOMNodeInserted", function(event){ var target = event.srcElement || event.target; if (target && target.tagName.toLowerCase() == 'input') { // do what you want to do here.... } }); 

I would prefer a little easier in your case: put your initialization logic in a separate function and call this function each time after manipulating the DOM. Inside this function, add the value of the class or data to each initialized element and verify that this class is initialized only once:

 function init() { $('.input_box').not('.initialized').each( function() { var ac = $(this).addClass('initialized').autocomplete(acOptions); }); } 
+2
source

All Articles