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
»

How to Dynamically Trim Text Using jQuery

This easy beginners jQuery tutorial demonstrates how you can use ...

article image
»

jQuery Snippets: Getting the Current Year

Here’s a fun, simple, and incredibly useful jQuery that you can ...

article image
»

jQuery Snippets: How to Conditionally Enable Submit

One easy way to prevent users from submitting an empty form in a ...

article image
»

How to Use Google Analytics with jQuery Mobile

jQuery Mobile is an HTML5 based web-page framework that’s ...

article image
»

jQuery Snippets: Using jQuery to Check All Boxes

When you’ve given your users a ton of checkbox input fields ...

article image
»

Useful jQuery Code Snippets for Working with Images

Images are an essential part of any website and sometimes working ...

article image
»

How to Use jQuery to Check if Cookies are Enabled

A cookie (not the kind with chocolate chips) is a small piece of data ...

article image
»

A Beginner’s Guide to jQuery’s Selectors

We talk a lot about event methods on this site, but not so much about ...

article image
»

Add Keyboard Shortcut to Anchor Tag Using jQuery

Making a user friendly website can be quite a challenging task. There ...