What's the recommended way to create an HTML elemnt and bind a listener to it using jQuery?

Posted by Bytecode Ninja on Stack Overflow See other posts from Stack Overflow or by Bytecode Ninja
Published on 2010-06-14T20:19:53Z Indexed on 2010/06/14 20:22 UTC
Read the original article Hit count: 159

At the moment I achieve this using something like this:

var myElem = "<tr id='tr-1'><td>content</td></tr>";
$("#myTable").append(myElem);
$("#tr-1").click(function() {
  // blah blah
});

Traditionally, when I wasn't using jQuery, I used to do something like this:

var myElem = document.createElement(...);
var myTable = document.getElementById("myTable");
myTable.appendChild(myElem);
myElem.onclick = function() {
  // blah blah
}

The thing is, in the second approach I already have a reference to myElem and I don't have to scan the DOM ($("#tr-1")) to find it, like the jQuery approach, and hence it should be much faster especially in big pages. Isn't there a better jQuery-ish way to accomplish this task?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery