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?
You can shrink it down/speed it up a bit like this:
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.