Wednesday 20 July 2011

jQuery selectors

jQuery offers a powerful set of tools for matching a set of elements in a document.

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\\.bar").

All Selector jQuery('*')
Selects all elements.

Attribute Equals Selector [name="value"]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
$('input[type="radio"]') //selects all radio buttons in the document

Attribute Starts With Selector [name^="value"]
Selects elements that have the specified attribute with a value beginning exactly with a given string.
$('div[id^="inputfield"]') //selects all DIVs whose id starts with "inputfield"

Child Selector (“parent > child”)
Selects all direct child elements specified by "child" of elements specified by "parent".
$("div.inputfield > input.ageBox") //select all input fields with class "ageBox" within DIVs with class "inputfield"

Descendant Selector (“ancestor descendant”)
Selects all elements that are descendants of a given ancestor.
$("form input") //selects all input field in the form

Class Selector (“.class”)
Selects all elements with the given class.

Element Selector (“element”)
Selects all elements with the given tag name

ID Selector (“#id”)
Selects a single element with the given id attribute.

Has Attribute Selector [name]
Selects elements that have the specified attribute, with any value.
$('div[id]') //Selects all DIVs with Ids

:first-child Selector
Selects all elements that are the first child of their parent. While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

$("div span:first-child").css("text-decoration", "underline")

last-child selector
Selects all elements that are the last child of their parent.While :last matches only a single element, :last-child can match more than one: one for each parent.

Multiple Attribute Selector [name="value"][name2="value2"]
$('input[id][name$="address"]') //Finds all inputs that have an id attribute and whose name attribute ends with "address"

Multiple Selector (“selector1, selector2, selectorN”)
Selects the combined results of all the specified selectors.

Click here to read more about jQuery selectors from jQuery API

No comments:

Post a Comment