I just learned how to do the ‘document.getElementById’ counterpart in jQuery (and it’s more powerful). My question is, is it okay to use it everytime or every line of code? Here’s how I use it now:
$('#MyParentElement').html('<tr id="' + $('#MyElement').val() + '"><td>' + $('#MyElement').val() + '</td></tr>';
Isn’t better if I do something like using a variable to reference the object?
var x = $('#MyElement');
$('#MyParentElement').html('<tr id="' + x.text() + '"><td>' + x.text() + '</td></tr>';
Note that I’m more concern of the performance, not the cleanliness of the codes.
DOM selection is expensive. Cache it.
Here’s a jsPerf test. In Chrome 13 on Mac OS X, the variable reference is over 1,000 times faster.
This is not only due to the DOM selection of course, but also the construction of the jQuery object.