Take the 2-minute tour ×

Right so I guess the common sense is that for elements you're going to be accessing a lot, the best way is to cache them like so:

var myEl = $('.myclass');

And then you can just access $(myEl) in the future and you don't need to search the DOM again, correct? Ok lets say I have a fairly complex html structure where I need to access several different elements a lot, like 20-30. It's very ugly todo this type of thing 30 times!

var elA = $('.myela'),
    elB = $('.myelb');

Etc etc, you get the idea.. so is there anything "bad" in doing it like this, keep the same class on all those elements, but give them an unique id, then do this:

var myElementObject={};
     myElementObject[$(this).attr('id')] = $(this);

This way it's like I get an object.whateverId and thats the cached element, so now I can use them as I like without re-querying the DOM all the time, is this assumption correct, is this a bad practice? How do you guys go about it?


share|improve this question

2 Answers 2

up vote 3 down vote accepted

If you're going to assign ids, then just use $('#id') since it uses getElementById which is very fast and probably is not much slower than putting them in some object hash.

Also consider applying a common class to these elements or grouping them in some other way so that you can cache $('.mycommonclass')

share|improve this answer
Exactly what I am doing with ".myelems", which in my description would be the common class, but yeah if $('#id') is so fast, why do people go on about "best" practices and "always" cache your elements? This is the thing I don't get, should I just always cache the elements I use a lot or not bother? Does it really impact performance a lot? I can't really find a clear answer on that. –  neph Feb 16 '11 at 1:37
@nepth I typically cache items if I'm about to do a lot of operations on said item. Like for example if I'm about to access the same item in a loop. Also a good idea to cache less performant queries like find/parents/css based queries if you're going to use them several times. I wouldn't necessarily cache queries globally though. –  Vadim Feb 16 '11 at 1:42
Yeah I suppose that makes sense! –  neph Feb 16 '11 at 1:45

It's a good way to do it if you're sure that you're going to access these elements(else it would be wasted resources). Another small thing: it would be best if you access the element in your first example by using myEl and not $(myEl) since $(myEl) has to execute a function(jQuery).

share|improve this answer
Actually, it's because myEl is already wrapped in a jQuery object. You don't have to do it twice. –  Richard Marskell - Drackir Feb 16 '11 at 1:34

Your Answer


