I know that ID is a faster selector than class in Javascript. But what if I cache the selector? When the selector is cached, would it differ in speed if it’s a class selector, or will it be as fast as the id selector?
Example:
<div class=”myclass”></div>
<div id=”myid”></div>
var $myclass = $('.myclass');
var $myid = $('#myid');
Will $myid be faster than than $myclass?
The cached reference to a DOM node
is always the fastest possible way. So once you have a reference stored, it makes no difference how it did get there.
Imagine there is a bridge between your Javascript world and the DOM world. Each time you want to access an element (a "citizen") from Javascript in the DOM world, you need to cross that bridge.. but that is not for free.. you need to pay a pretty expensive toll.
So you should only go that way once and therefore only pay once.
If you know the exact position of the element (which is stored in a variable) you can just access it in no time.
You have those stored in variables. So the speed will be the same for both.
The performance hit will occur when you are iterating DOM to get elements. At that time ID selector will be faster than class selector.
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