jQuery Tips

jQuery Tips Summary

Using multiple selector

selector1 or selctor2

var el = $(".a", "#test");

selector1 and selector2

var el = $(".b" + "#test");

Add check to checkbox

$("#element").attr('checked', true);

If you want to remove check, use removeAttr


Check whether the checkbox is checked or not

var checked = $('#element').is(':checked');

checked is true or false(boolean)

How to make a lot of table row

To use clone technique.
Prepare tr element as with hidden attr(hidden(display:none)). This is row template.

var tr = $(element).clone();

Display Size

window object

winHeight = $(window).height();
winWidth = $(window).width();

Save data in DOM


$("").data("key", data);

data is javascript object. Any type is fine.


This data is combined with DOM


Use id
id is faster than other selectors.


Use class name ant element name together.
This is faster than single class name use.


Simple is best!

$("#nav a");        // Fast
$("#nav ul li a");  // A bit slow


$("#nav").find("a");   // Fast
$("#nav a");          // A bit slow

Cache jQuery object using var if use multiple

var element = $("#id");

Reduce DOM operations

var ul = $("ul");
var lis;
for ( var i=0;i < 50;i++ )
     lis += '<li>' + i + '<li>';