Search code examples
jquery-1.4

What is the difference between these two jQuery references and why does one not work with .live?


EmployeeId is the id of a select element with a set of options. This approach will not work:

var tar = document.getElementById("EmployeeId");
$(tar).live("click", function(){
 console.log("Changed");
});

However, this approach does:

$("#EmployeeId").live("click", function(){
 console.log("Changed");
});

What is the difference between $("#EmployeeId") and $(tar)?? I was under the impression there was no difference between the two. Moreover, when I try

console.log($(tar));
console.log($("#EmployeeId"));

The same exact thing is sent to the console.

What am I missing, what is different, why is one approach not attaching the event handler?


Solution

  • .live needs the selector to work with, since it binds the event handler to document and then tests whether the origin (or any element in the path) of the event matches the selector.

    If no selector is provided, it won't work. That's why chaining methods like $('foo').children().live(..) does not work either.

    Since jQuery 1.7, .live is deprecated for various reasons listed in its documentation: http://api.jquery.com/live/.

    Alternatives are .on (1.7) and .delegate (1.4.2).