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={};
$('.myelems').each(function(){
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?
Thanks!
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With