Bind select2 to dynamically generated elements

Last Updated: March 31, 2019

In the course of our WordPress development, we often generate new <select> elements on the fly, after the DOM has been loaded jQuery’s document ready() has already run.

Most tutorials demonstrate binding <select> with something like this:

jQuery( function() {
	jQuery( "select.select2" ).select2({
		// any options go here
	});
});

The challenge is that this binding will not be applied to any <select> elements generated after the document has already loaded and the binding has occurred.

Now, if you’ve spent any substantial time with jQuery, this one might already be filed under “obvious”, but it took me some googling and trial-and-error to figure it out and I hope it was helpful.

You could, of course, manually re-execute the same binding to all newly generated content, but this is tedious and error-prone. Far better to use the .on event:

jQuery( function() {
	jQuery( "body" ).on( "DOMNodeInserted", 'select.select2', function () {
		jQuery( this ).select2({
			// any options go here
		});
	});
});

Chris Aram

I'm a developer who specializes in whipping your technology into shape so that it makes your professional and personal life better.