Saturday, July 9, 2011

Selecting Elements in jQuery

The jQuery library allows you to select elements in your XHTML by wrapping them in $("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery:



$("div"); // selects all HTML div elements

$("#myElement"); // selects one HTML element with ID "myElement"

$(".myClass"); // selects HTML elements with class "myClass"

$("p#myElement"); // selects HTML paragraph element with ID "myElement"

$("ul li a.navigation");// selects anchors with class "navigation" that are nested in list items



jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors:

$("p > a"); // selects anchors that are direct children of paragraphs

$("input[type=text]"); // selects inputs that have specified type

$("a:first"); // selects the first anchor on the page

$("p:odd"); // selects all odd numbered paragraphs

$("li:first-child"); // selects each list item that's the first child in its list



jQuery also allows the use of its own custom selectors. Here are some examples:

$(":animated"); // selects elements currently being animated

$(":button"); // selects any button elements (inputs or buttons)

$(":radio"); // selects radio buttons

$(":checkbox"); // selects checkboxes

$(":checked"); // selects checkboxes or radio buttons that are selected

$(":header"); // selects header elements (h1, h2, h3, etc.)

No comments:

Post a Comment