Skip to content Skip to sidebar Skip to footer

How Do You Cache A Dom Element?

I understand that referencing $('#Counter') over and over is a bad idea because you are 'jumping into the DOM each time'. But is this any better? Counter = $('#Counter'); And then

Solution 1:

For the case you described, it is preferrable to save jQuery object in a variable before entering the iteration statement, where you repeatedly use this object. It will prevent of traversing the DOM tree at each iteration. Besides it can be insensible for searching by ID, but querying by class name or using compound selectors may sufficiently decrease the performance.

var $Counter = $("#Counter");
for (...) {
    $Counter.val(function(i, val) { return +val + 1; });
    ...
}

Pay attention to using function as argument of val() which is more reasonable in this case.

Post a Comment for "How Do You Cache A Dom Element?"