开发者

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开发者_StackOverflow 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.


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜