views:

35

answers:

3

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?

+7  A: 

You can shrink it down/speed it up a bit like this:

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

This takes out the need to find the element, and also you're dealing with a document fragment until you actually call .appendTo(), making it much faster to do DOM operations.

There's also $(html, props) version since 1.4 that doesn't quite work for your example, but is even more terse in some situations that you may want to check out.

Nick Craver
Could you please explain a little bit more what do you mean by "and also you're dealing with a document fragment"? Thanks.
Bytecode Ninja
@Bytecode - Sure! When you do [`$(html)`](http://api.jquery.com/jQuery/) you're creating a [document fragment](http://developer-stage.mozilla.org/En/DOM/DocumentFragment) that's much quicker to work with, you're not working with the DOM, but a tiny fragment containing nodes that's much quicker to operate on, get it like you want then you insert it into the full DOM/your page. It's just a more efficient (usually) way of dealing with things...jQuery also caches the fragments based on the html string (up to 512 bytes), so you can re-use them, making node creation from an html string much faster.
Nick Craver
@Nick: Thanks a lot for the explanation!
Bytecode Ninja
A: 

Just "cast" myElem into a jQuery object?

$(myElem).click(function() { ... });
Jaanus
+1  A: 

use live events. now when you add the element to the dom the live event gets added to the new element.

$(document).ready(function() {
  $("#tr-1").live("click", function() { 
    // blah blah 
  }); 
}
John Hartsock
Thanks, I didn't know about live events. However my goal was to eliminate the `$("#tr-1")` scan.
Bytecode Ninja
Not sure what the benefit of using live() on an element which there is only ever going to be one of on a a page. It seems a bit more useful for adding events to a class or tag group of elements.
paulj