jQuery Tip: Cache your selector

We all can use a little help when it comes to writing truly good code no matter what language we use and JavaScript with jQuery is no exception. One thing I have seen many times (and am guilty of myself) is constantly searching and researching for selectors. While this technically is not a “bad thing”, if left unchecked, it could slow your application down.

For example, assume you have a paragraph that you want to change the way it looks. You may do something like this:


$("#paragraph1").css("color", "red");
$("#paragraph1").css("background-color", "blue");
$("#paragraph1").css("font-size", "10px");
$("#paragraph1").css("font-weight", "bold");

While this will succeed in making your paragraph extremely ugly, you have forced jQuery to search for the paragraph in your HTML document four times. There is a way to make jQuery search for the paragraph only once and still have all the same changes take place. You can do that by caching the selector. To do that you store the selector in a variable and then use that variable to make the changes. For example:


var para1 = $("#paragraph1");
para1.css("color", "red");
para1.css("background-color", "blue");
para1.css("font-size", "10px");
para1.css("font-weight", "bold");

Not a major change to the code, but getting in the habit of programming this way can make sure your code runs as efficiently as possible.

Sorry, Comments are Closed.

You'll have to take it up with the author...