Caching Elements in jQuery

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.



Responsive Menu
Add more content here...