To clear a few things up about adding events to elements that are injected dynamically into the DOM (ie – they don’t exist when the page is loaded).

Best Practice Methods

  • Use .Bind() and .Live() instead of .Click().
  • Use .Bind() for static DOM elements (elements that are loaded with the page).
  • Use .Live() for dynamic DOM elements (elements changed/inserted via JavaScript).


In this example it is an ordered list which appears once you have loaded a JSON file into the tool. Then a mouse hover event has been applied to every component in the DOM.

/*mouse IN hover to show path of node*/
$('#div li').live('mouseenter', function () {
    //do something

/*click event for hyperlink*/
$('#div a').bind('click', function (e) {
	//don't follow the hyperlink href
    //do something else

Online Demo

Other Live Options

There is a live query plugin which can handle these for you with just one declaration. LIVE QUERY PLUGIN: I’ll write more about the live query plugin when i get the chance to check it out properly and test it.

Also see: Binding to elements with the same id

Tags: jquery add event to dynamic dom element
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.