Search code examples
jquerylive

differences between $("#element") and $(document.getElementById("element"))?


I am experiencing some weird behavior in jQuery (v1.7):

I am trying to set an event listener to an element that actually gets replaced at some point via ajax.

$(document.getElementById('element')).live('click', function() {
    // do something on click
});

while this works fine with other methods, the live method refuses to run. when replacing this with the native jQuery selector it works. Why?

$("#element").live('click', function() {
    // do something on click
}); 

Solution

  • live doesn't work this way. The event bubbles up to the document and then the target of the event is examined to see if it matches the selector.

    It's likely that the element you're listening for events on does not exist when you bind the event handler, so getElementById returns nothing.

    When you think about the semantics of live it doesn't make sense to pass it a DOM element.