Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 587
Pinkie Avatar asked Feb 24 '23 08:02

Pinkie


1 Answers

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

like image 128
Kris Ivanov Avatar answered Mar 30 '23 08:03

Kris Ivanov