In jQuery, how to attach events to dynamic html elements?

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with ‘myclass’ as an argument.


So instead of…

$(".myclass").click( function() {
    // do something

You can write…

$('body').on('click', 'a.myclass', function() {
    // do something

This will work for all a tags with ‘myclass’ in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
    alert( $(this).text() );

As long as the ul tag exists this will work (no li elements need exist yet).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: