jQuery Tips and Tricks

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");
});

Leave a Comment