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:
highlightedItems = $(
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.
highlightedItems = $(li.highlighted);
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