The biggest advantage of jQuery is its ability to easily select DOM elements using CSS-like selectors. We can write code to select by element ID or class, etc. Here is an example of how to select all elements with a given class name:
Sometimes, we need to perform operations on the result of a selection. Let's say we need to remove the highlight when an item is clicked and set another class. This is one way of doing it:
As you can see, we have used the same jQuery selector three times in the code above. As this functionality is abstracted by jQuery it is easy to write the code above and get done with this, as it works. However, developers should know that performing a selection in jQuery can be an expensive operation. Every time we invoke a selector, the browser performs a search through the DOM and returns a collection of the elements we want. This may take a while.
This is why, it is always recommended that we cache the results of our jQuery selections in a variable. The code above can be rewritten to save the selection and then use it to do what needs to be done.
Now we perform the selection only once and avoid the additional processing that is done of performing it. In case you are not adding or removing DOM elements, you should always cache the results of your jQuery selectors.
Back To Top
To submit feedback, please update your cookie settings and allow the usage of Functional cookies.
Your feedback about this content is important
Copyright © 2022 Progress Software Corporation and/or its subsidiaries or affiliates.
All Rights Reserved.
Progress, Telerik, Ipswitch, and certain product names used herein are trademarks or registered trademarks of Progress Software Corporation and/or one of its subsidiaries or affiliates in the U.S. and/or other countries. See Trademarks for appropriate markings.
Powered by Progress Sitefinity