0

I have a list with the id #list with no list items in it. In my jQuery script, I have a function that sets the HTML inside of #list to some list items.

$('#list').click(function() {
    $('#list').html("<li> blah </li> <li> blooh </li>");
});

But afterwards, when I try to manipulate $('#list li'):

$('#list li').mouseenter(function() {
    this.style.backgroundColor = "red";
});

it doesn't seem to work. Any ideas?

  • 1
    possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Mar 29 '14 at 00:33
  • 1
    and [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Felix Kling Mar 29 '14 at 00:33

2 Answers2

0

Its not working because the click handler is only being applied to things that are in the DOM. Try this:

$('#list').delegate('li','click',function(){
   this.style.backgroundColor = "red";
});

Delegate will bind elements that do not yet exist in the DOM.

Mike Furlender
  • 3,869
  • 5
  • 47
  • 75
0

If using jQuery v1.7+, use .on() in its delegated form like :

$('#list').click(function () {
    $('#list').html("<li> blah </li> <li> blooh </li>");
}).on("mouseenter", "li", function () {
    this.style.backgroundColor = "red";
}).on("mouseleave", "li", function () {
    this.style.backgroundColor = "white";
});

JSFIDDLE

Notice that you can chain the events

JFK
  • 40,963
  • 31
  • 133
  • 306