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
»

7 Responsive jQuery Dropdown Menu Plugins

Dropdown Menu Plugins Dropdown menus are mostly used for website ...

article image
»

20 Stylish and Modern jQuery Tooltip Plugins

jQuery Tooltip Plugins Tooltips are a great option for showing extra ...

article image
»

15 Newest jQuery plugins for responsive website

Due to the proliferation of smartphones and tablets, responsive ...

article image
»

How to use Redux with jQuery

State management is one of most integral parts of any software and a ...

article image
»

Fade HTML Table Row on Hover Using jQuery

HTML tables are the ideal choice for displaying data in tabular form. ...

article image
»

Drag and Drop HTML Table Rows Using jQuery

HTML tables are the preferred UI option for displaying data. Sorting, ...

article image
»

Top 5 Best JavaScript Template Engines

Template engines help in the decoupling of HTML and JavaScript code ...

article image
»

3 jQuery/JavaScript Plugins for Push Notifications

Push notifications started from the mobile business but this ...

article image
»

Create Smooth Animation Using jQuery’s “stop()”

Making Quick Work jQuery’s animate() method is a quick way to ...