jQuery Tips and Tricks

jQuery Tips and Tricks


Shorthand for the ready-event by roosteronacid
Line breaks and chainability by roosteronacid
Nesting filters by Nathan Long
Cache a collection and execute commands on the same line by roosteronacid
Contains selector by roosteronacid
Defining properties at element creation by roosteronacid
Access jQuery functions as you would an array by roosteronacid
The noConflict function – Freeing up the $ variable by Oli
Isolate the $ variable in noConflict mode by nickf
No-conflict mode by roosteronacid

Data Storage

The data function – bind data to elements by TenebrousX
HTML5 data attributes support, on steroids! by roosteronacid
The jQuery metadata plug-in by Filip Dupanović


Optimize performance of complex selectors by roosteronacid
The context parameter by lupefiasco
Save and reuse searches by Nathan Long
Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors by Andreas Grech


Check the index of an element in a collection by redsquare
Live event handlers by TM
Replace anonymous functions with named functions by ken
Microsoft AJAX framework and jQuery bridge by Slace
jQuery tutorials by egyamado
Remove elements from a collection and preserve chainability by roosteronacid
Declare $this at the beginning of anonymous functions by Ben
FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN by Colour Blend
Judicious use of third-party jQuery scripts by harriyott
The each function by Jan Zich
Form Extensions plug-in by Chris S
Asynchronous each function by OneNerd
The jQuery template plug-in: implementing complex logic using render-functions by roosteronacid


Solution 1:

Creating an HTML Element and keeping a reference

var newDiv = $("<div />");

newDiv.attr("id", "myNewDiv").appendTo("body");

/* Now whenever I want to append the new div I created, 
   I can just reference it from the "newDiv" variable */

Checking if an element exists

if ($("#someDiv").length)
    // It exists...

Writing your own selectors

$.extend($.expr[":"], {
    over100pixels: function (e)
        return $(e).height() > 100;

$(".box:over100pixels").click(function ()
    alert("The element you clicked is over 100 pixels height");

Solution 2:

jQuery’s data() method is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.

Solution 3:

Nesting Filters

You can nest filters (as nickf showed here).


Solution 4:

I’m really not a fan of the $(document).ready(fn) shortcut. Sure it cuts down on the code but it also cuts way down on the readability of the code. When you see $(document).ready(...), you know what you’re looking at. $(...) is used in far too many other ways to immediately make sense.

If you have multiple frameworks you can use jQuery.noConflict(); as you say, but you can also assign a different variable for it like this:

var $j = jQuery.noConflict();


Very useful if you have several frameworks that can be boiled down to $x(...)-style calls.

Solution 5:

Ooooh, let’s not forget jQuery metadata! The data() function is great, but it has to be populated via jQuery calls.

Instead of breaking W3C compliance with custom element attributes such as:


Use metadata instead:

  class="validation {validate: email, minLength: 2, maxLength: 50}" />

    jQuery('*[class=validation]').each(function () {
        var metadata = $(this).metadata();
        // etc.

Solution 6:

Live Event Handlers

Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load:

$('button.someClass').live('click', someFunction);

This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.

Likewise, to stop the live event handling:

$('button.someClass').die('click', someFunction);

These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases.

For more info see the jQuery Documentation.

UPDATE: live() and die() are deprecated in jQuery 1.7. See http://api.jquery.com/on/ and http://api.jquery.com/off/ for similar replacement functionality.

UPDATE2: live() has been long deprecated, even before jQuery 1.7. For versions jQuery 1.4.2+ before 1.7 use delegate() and undelegate(). The live() example ($('button.someClass').live('click', someFunction);) can be rewritten using delegate() like that: $(document).delegate('button.someClass', 'click', someFunction);.