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 Disable Right-Click Menu Using jQuery

There can be dozens of reasons why you may want to disable right ...

article image
»

How to Optimize jQuery Code for Better Performance

jQuery is the most popular client side library, in fact almost every ...

article image
»

Using Head.js to Load All Your JavaScript

In the past few years, client side frameworks/libraries have become ...

article image
»

How to Detect Browser Using jQuery

One of the more frustrating parts of creating a new web project is ...

article image
»

Convert Images to Black and White using jQuery

Converting an image to black and white is no longer a manual event. ...

article image
»

How to Use jQuery to Set Textarea Max Length

If you have a textarea field on any of your sites, it might be a good ...

getTable
»

15 Awesome jQuery Table Plugins

Tables are the most preferred way to display data because rows and ...

article image
»

How to Dynamically Open External Links in New Window

Any web developer will probably know that using the ...

article image
»

How to Use jQuery’s .not() Method

jQuery’s .not() method is a method that allows you to return ...