July 13, 2010

Basic (CSS) JQuery Selectors

I love JQuery. Oh so easy to use, excellent documentation, and an abundance of third-party plugins and widgets ready made for almost anything you could ever need. Of course, one of the most important parts of the library are JQuery's selectors, easy CSS-like syntax to select specific DOM elements to manipulate. Here is my personal JQuery selector reference sheet, drawn from the JQuery API, the web, and other JQuery books/reference sheets I've read. These selectors use near-CSS syntax, they should be relatively easy to understand.

Matches anything


Matches element with tagName (ex. a, span, etc)


$('a') //matches all links
$('span') //matches all spans

Matches element with id elementId (with optional tagName)


$('div#header') //matches div element with id = header

Matches element with class elementClass (with optional tagName)


$('a.menu-link') //matches links with class = menu-link

Matches CSS family/descendent patterns

$('A B') //B elements that are a descendant of A
$('A > B') //B elements that are direct children of A
$('A:has(B)') //A elements that have B as a descendant

$('#header a') //matches links inside element id=header

Matching attributes

$('tagA[attr]') //tagA elements with an attr attribute
$('tagA[attr=value]') //tagA elements with attr is equal to value
$('tagA[attr^=startsWith]') //tagA elements with attr starts with startsWith
$('tagA[attr$=endsWith]') //tagA elements with attr ends with endsWith
$('tagA[attr*=containsThis]') //tagA elements with attr contains containsThis

$('img[alt]') //matches img elements with an alt attribute
//matches checkboxes whose names start with ch_ (ex. ch_1, ch_2,...) 

That's it for now, I'll post again soon with JQuery custom selectors (things like :disabled, :hidden, etc. that jQuery has added to its library to make things easier on developers) !