Quick Jquery: How to reduce DOM traversing

Ofcourse, less the DOM will get traversed quick will be the output. Therefore here is the trick to cache the element in jquery so as to reduce traversing.

Here we go:

Wrong Way

var myElement = $('#anyElement');
$('#anyElement').show();
$('#anyElement').addClass('anyClass');

.

.

Right Way

var myElement = $('#anyElement');
myElement.show().addClass('anyClass');

And its done

Scroll to Top