X

LATEST #JQUERY NEWS

Top Tips for Optimizing Your jQuery Selectors


When your jQuery runs slow as a result of poorly organized or clunky code, it can really negatively affect your users’ experience. One easy way to optimize your jQuery and to help avoid slow-running code is to make sure that the selectors are constructed as well as they possibly can be. To make sure your selectors aren’t slowing down your code, apply the following tips to your jQuery:

1. When selecting elements, select by ID, not by class. Because of the native getElementById method, most browsers can select an element by ID much quicker than they can with a class, because using a class as a selector results in the jQuery having to move through the DOM.

$("#div");

NOT

$(".div");

2. If you are going to use a class as a selector, indicate the HTML tag type before the class name. The reason for this is similar to the reason for using elements rather than classes: there is a native getElementByTag method that makes it easier and quicker for the browser to find the class if it’s preceded by its HTML tag type.

$("h2 .green");

NOT

$(".green");

3. Cache your elements as objects before you use them. If your browser only has to locate your selector once, it will make your code a lot quicker. To do this, you need to save an element as a variable in your jQuery that can be reused over and over. See below for an example:

var firstParagraph = $("#firstP)";
$firstParagraph.slideUp();
$firstParagraph.slideDown();

Recently Published

article image
»

jQuery Snippets: How to Add/Remove Classes After Delay

In your projects, there can often be instances of wanting to change ...

article image
»

jQuery Snippets: Back to Top Button

One common way to use jQuery is to add a useful and functional ...

article image
»

jQuery .on() Method: the Issue of Dynamically Added Elements

The jQuery .on() method is the recommended way for attaching events ...

article image
»

How to Use jQuery to Test CSS3 Browser Support

The tricky thing about using CSS properties (especially newer ones ...

article image
»

jQuery Snippets: Check/Un-Check All Function

This easy-to-implement jQuery code snippet is super useful, and can ...

article image
»

Useful jQuery Code Snippets for Handling CSS

If you’re not already familiar with code snippets, they are ...

article image
»

Using Method Chaining in jQuery

Using method chaining in jQuery helps to ensure that your code stays ...

article image
»

jQuery’s .children() Method

Just like in CSS, it’s possible to use jQuery to select the ...

article image
»

jQuery’s .click() Method

With jQuery, it’s super easy to make something happen as a result ...