If you cache your jQuery elements, it means that you store an element as a variable so that you can re-use that element without your jQuery having to re-query the DOM in search of it every time you want to apply some code to that element. Itâ€™s not always necessary, but in cases where you know youâ€™ll be using certain elements a lot in your code, itâ€™s not a bad idea to cache them, because thatâ€™ll help your code work faster and more efficiently.
Hereâ€™s how you would cache an element, itâ€™s actually super simple! For this example, letâ€™s cache a class called .main:
Â var main = $(â€œ.mainâ€);
Thatâ€™s literally all it takes to cache an element. Then when you want to use it later, you just have to refer back to the name that you gave you variable, like this:
Â main.css(â€œcolorâ€, â€œblueâ€);
The code above will change the CSS so that the color of the text in the .main class is blue. You can cache as many selectors as you like and give the variables whatever name you like, and this should help keep your code light and clean.