So why are we supposed to cache jQuery objects?
In the following scenario:
var foo = $('#bar');
foo.attr('style','cool');
foo.attr('width','123');
$('#bar').attr('style','cool');
$('#bar').attr('width','123');
Why is the first option so much better than the second option?
If it's because of performance, how does it reduce usage?
$('#bar')multiple times, in your example, it's used just 1 time. So it should not have any advantage here.#lookup, it is a pretty efficient getElementbyID), but purely for the sake of having mentioned it: JQuery helps by having its functions re-return the object, so attr returns the same object as was used, making the following possible:$('#bar').attr('style','cool').attr('width','100');. Having the same advantage of reusing the query object.