What are the fastest/slowest selectors in jQuery ?
jQuery Selectors are used for selecting and manipulating HTML elements.
In jQuery, there are mainly three selectors.
- ID selector
- Class selector
- Element selector
Before moving forward, first, let’s briefly see how these selectors are used.
Element Selector: jQuery element selector selects the element on the basis of their name.
This selector is basically used when we have to work on a single element because an ID should be unique within a web page.
Class Selector: The jQuery .class selector selects the element or the set of elements whose class matched. The same class name is allowed for different HTML elements.
Let’s write some code to see how actually fast these selectors are?
Example: We will write a program that will perform the same task using different selectors, let’s see how much time they are taking.
ID Selector : 597 milliseconds Class Selector :751 milliseconds Element Selector : 741 milliseconds
After seeing the result of the above code, it is crystal clear that the ID selector is the fastest. The class and element selector is taking almost the same time.
What are the fastest/slowest selectors in jQuery?
Among all three selectors, the ID selector is the fastest selector because an ID of any HTML element will be unique within the web page and when a web page loaded, the browser will start searching for the element with a specified ID and an ID is unique, so the moment the browser finds the element with the specified ID, it will stop searching.
But in the case of a class selector, multiple elements can have the same class name and due to this, the browser has to traverse the whole DOM to find out each element having a specified class name. Due to this, the class selector is considered the slowest selector.
If you have a lot to perform on the web page, and it’s not possible to use an ID selector every time, then the best way is caching. Fetch the selectors once and store them for further use.
Note: If we consider today’s modern browsers, then these selectors are equally fast because in modern browsers class names are hashed internally, and we have .getElementsByClassName() whereas in older browsers there is no function similar to .getElementsByClassName() and that’s the reason .class name is parsed internally to jQuery and then every element of DOM is traversed and checked for the class name.