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
1 2 3 | var myElement = $('#anyElement'); $('#anyElement').show(); $('#anyElement').addClass('anyClass'); |
.
.
Right Way
1 2 | var myElement = $('#anyElement'); myElement.show().addClass('anyClass'); |
And its done


Comments
Hello,
maybe this way :
$(‘#anyElement’).show().addClass(‘anyClass’);
is it different ?
Bye,
Kaimite
@Kaimite: yes, it’s different because I can use myElement variable a lot of times instead your solution is good for one only use.
Good tip!
Right way ™:
var myElement = $(‘#anyElement’).show().addClass(‘anyClass’);
@Kaimite The example was a rather simplistic one, the point however was the reuse the variable created rather than to search through the dom repeatedly.
However… the $(‘#’) lookup is quick enough for this not to really matter.
A more apt example would have been to use classes or something like this even:
`var commentArea = jQuery(‘textarea[name~=comment]:eq(10)’);`
Where you would actually wind up with some performance enhancements.
Unless of course you do var myElement = $(‘#anyElement’).show().addClass(‘anyClass’);
=c)
Meaning anytime we do a $(‘someelement’) we are re-searching the DOM and slows down performance?
Nice tip, thanks
Hi, your contact form doesn’t seem to be working. We did like to advertise on your blog, do contact us back if interested.
good idea but you should explain further with samples.