Pinkie
Pinkie

Reputation: 10256

jQuery caching selectors

I have div with id #wrapper and all element are inside it. I'm caching wrapper by doing

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

Now any time i want to make a selector or reference an element, i do

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

By doing this i avoid wrapping with jQuery object again, so any selector i do in the future will be based on the cached $wrapper. But on the other when i use find() with the cached $wrapper, i know it will search all elements inside #wrapper. My questions is whic is better better, use cached variable along with find then issue click event, or just simply do $('#whatever').click(..

whatever can be either a class or id.

Upvotes: 4

Views: 5443

Answers (4)

Willabee
Willabee

Reputation: 31

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

$('#whatever', $wrapper)

searches the DOM only in the context of $wrapper

Don't search the whole tree when you can search a single branch or twig.

Upvotes: 2

user229044
user229044

Reputation: 239541

The two are not completely equivalent. Your caching version is actually the same as $("#wrapper #whatever"), and won't match the element with id whatever if it isn't contained in the wrapper div.

If you always intend for the #whatever element to be within the #wrapper, then $('#whatever') is actually probably faster than your cached version - finding elements by ID involves a single function call, getElementById, which is available in all browsers, while your cached version involves checking the hierarchy to make sure the matched #whatever element descends from #wrapper.

Upvotes: 2

Kris Ivanov
Kris Ivanov

Reputation: 10598

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

Upvotes: 2

CarlosZ
CarlosZ

Reputation: 8679

Performance wise it is better to cache the "wrapped" version of the DOM element. Otherwise you'll be traversing the DOM every time you do $("#myElem") which can get very expensive if your DOM is really big or you are doing it a lot of times.

Upvotes: 2

Related Questions