JQuery Cache Selectors

I have a div with id #wrapper and all the elements inside it. I cache the shell by doing

 var $wrapper = $('#wrapper'); 

Now, when I want to make a selector or link to an element, I do

 $wrapper.find('#whatever').click(.... 

Having done this, I will no longer wrap the jQuery object, so any selector that I will do in the future will be based on $wrapper caching. But on the other hand, when I use find() with a cached shell $, I know that it will look for all the elements inside #wrapper . My questions are better, use a cached variable, and then find the click click event, or just do $('#whatever').click(..

whatever can be either a class or id.

+4
source share
4 answers

if you use it where whateverID is an ID , then $('#whateverID').click(.. will give you a slightly better performance, however if whateverCLASS is a class or something other than an ID , $wrapper.find('whateverCLASS').click(.... would be better, since the intersection would be limited to a specific container, which is a subset of the entire DOM

+2
source

Performance is better to cache a wrapped version of a DOM element. Otherwise, you will traverse the DOM every time you make $("#myElem") , which can become very expensive if your DOM is really big or you do it many times.

+2
source

These two are not completely equivalent. Your caching version is actually the same as $("#wrapper #whatever") , and will not match an element with id whatever if it is not contained in a div wrapper.

If you always want the #whatever element to be within #wrapper , then $('#whatever') is actually probably faster than your cached version - searching for elements by identifier includes one call to getElementById , which is available in all browsers, while your cached version includes hierarchy checking to make sure that the matching #whatever element #whatever omitted from #wrapper .

+2
source

How about $ ('selector', context), so ...

 $('#whatever', $wrapper) 

searches for the DOM only in the context of $ wrapper

Do not search the entire tree when you can search for a single branch or branch.

+2
source

All Articles