Sei sulla pagina 1di 6

Subscribe Now for FREE! refcardz.

com
tech facts at your fingertips

CONTENTS INCLUDE:

jQuery Selectors
n
What are jQuery Selectors?
n
Types of jQuery Selectors
n
Basic CSS Selectors
n
Custom jQuery Selectors
n
Matched Set Methods
By Bear Bibeault & Yehuda Katz
n
Hot Tips and more...

Basic CSS Selectors


What are jQuery selectors?
These selectors follow standard CSS3 syntax and semantics.
jQuery selectors are one of the most important aspects of the
Syntax Description
jQuery library. These selectors use familiar CSS syntax to allow
* Matches any element.
page authors to quickly and easily identify any set of page
E Matches all elements with tag name E.
elements to operate upon with the jQuery library methods.
Understanding jQuery selectors is the key to using the jQuery E F Matches all elements with tag name F that are descendants of E.

library most effectively. This reference card puts the power of E>F Matches all elements with tag name F that are direct children of E.

jQuery selectors at your very fingertips. E+F Matches all elements with tag name F that are immediately
preceded by a sibling of tag name E.
A jQuery statement typically follows the syntax pattern:
E~F Matches all elements with tag name F that are preceded
$(selector).methodName(); by any sibling of tag name E.

E:has(F) Matches all elements with tag name E that have at least one
The selector is a string expression that identifies the set of descendant with tag name F.
DOM elements that will be collected into a matched set to be
E.c Matches all elements E that possess a class name of c.
operated upon by the jQuery methods. Omitting E is identical to *.c.

Many of the jQuery operations can also be chained: E#i Matches all elements E that possess an id value of i.
Omitting E is identical to *#i.
www.dzone.com

$(selector).method1().method2().method3(); E[a] Matches all elements E that posses an attribute a of any value.

As an example, lets say that we want to hide the DOM element E[a=v] Matches all elements E that posses an attribute a whose value is
exactly v.
with the id value of goAway and to add class name incognito:
E[a^=v] Matches all elements E that posses an attribute a whose value starts
$(#goAway).hide().addClass(incognito); with v.

E[a$=v] Matches all elements E that posses an attribute a whose value ends
Applying the methods is easy. Constructing the selector with v.
expressions is where the cleverness lies.
E[a*=v] Matches all elements E that posses an attribute a whose value
contains v.

The wrapped set created by the application of a Examples


Hot selector can be treated as a JavaScript array for
n $(div) selects all <div> elements
Tip convenience. It is particularly useful to use array
indexing to directly access elements within the n $(fieldset a) selects all <a> elements within
wrapped set. <fieldset> elements
For example:
var element = $(img)[0];
Get More Refcardz
will set the variable element to the first element (Theyre free!)
in the matched set.
Authoritative content
jQuery Selectors

n Designed for developers


n Written by top experts
TYPES OF jQuery selectors
n Latest tools & technologies

n Hot tips & examples


There are three categories of jQuery selectors: Basic CSS
n Bonus content online
selectors, Positional selectors, and Custom jQuery selectors.
n New issue every 1-2 weeks

The Basic Selectors are known as find selectors as they are used
to find elements within the DOM. The Positional and Custom Subscribe Now for FREE!
Selectors are filter selectors as they filter a set of elements Refcardz.com
(which defaults to the entire set of elements in the DOM).

DZone, Inc. | www.dzone.com


2
jQuery Selectors
tech facts at your fingertips

Basic CSS Selectors, continued Positional Selectors, continued


Examples Syntax Description

n $(li>p) selects all <p> elements that are direct children B:odd Selects the odd elements within the set of elements defined by B.

of <li> elements B:eq(n) Selects the n-th element within the set of elements defined
by B. Starts at 0.
n $(div~p) selects all <div> elements that are preceded
B:gt(n) Selects elements within the set of elements defined by B
by a <p> element that follow the n-th element (exclusive). Starts at 0.

n $(p:has(b)) selects all <p> elements that contain a B:lt(n) Selects elements within the set of elements defined by B
that precede the n-th element (exclusive). Starts at 0.
<b> element
n $(div.someClass) selects all <div> elements with Examples
a class name of someClass n $(p:first) selects the first <p> element on the page
n $(.someClass) selects all elements with class name n $(img[src$=.png]:first) selects the first <img>
someClass element on the page that has a src attribute ending in .png
n $(#testButton) selects the element with the id value n $(button.small:last) selects the last <button>
of testButton element on the page that has a class name of small
n $(img[alt]) selects all <img> elements that possess n $(li:first-child) selects all <li> elements that are
an alt attribute first children within their lists
n $(a[href$=.pdf]) selects all <a> elements that n $(a:only-child) selects all <a> elements that are the
possess an href attribute that ends in .pdf only element within their parent
n $(button[id*=test]) selects all buttons whose id n $(li:nth-child(2)) selects all <li> elements that
attributes contain test are the second item within their lists
n $(tr:nth-child(odd)) selects all odd <tr> elements
You can create the union of multiple disparate within a table
Hot selectors by listing them, separated by commas, n $(div:nth-child(5n)) selects every 5th <div>
Tip in a single call to $(). For example, the following element
matches all <div> and <p> elements:
n $(div:nth-child(5n+1)) selects the element after
$(div,p) every 5th <div> element
While the following, matches all <div> elements n $(.someClass:eq(1)) selects the second element
with a title attribute, and all <img> elements with a class name of someClass
with alt attributes: n $(.someClass:gt(1)) selects all but the first two
$(div[title],img[alt]) elements with a class name of someClass
n $(.someClass:lt(4)) selects the first four elements
Positional Selectors with a class name of someClass
These selectors match based upon positional relationships
between elements. These selectors can be appended to any Note that the :nth-child selectors begin
base selector (which well denote by B) to filter the matches Hot counting at 1, while the :eq , :gt and :lt
based upon position. If B is omitted, it is assumed to be * Tip selectors begin with 0.
(the pool of all elements).

Syntax Description
jQuery Custom Selectors
B:first Selects the first element on the page matching the base
selector B. These selectors are provided by jQuery to allow for commonly
B:last Selects the last element on the page matching the base
used, or just plain handy, selections that were not anticipated
selector B. by the CSS Specification. Like the Positional Selectors, these
B:first-child Selects all elements from B that are first children. selectors filter a base matching set (which we denote with B).
B:last-child Selects all elements from B that are last children. Omitting B is interpreted as the set of all elements. These
B:only-child Selects all elements from B that are only children.
selectors may be combined; see the examples for some
powerful selector combinations.
B:nth-child(n) Selects all elements from B that are n-th ordinal children.
Starts at 1.
Syntax Description
B:nth-child(odd|even) Selects all elements from B that are even or odd ordinal
children. The first child is considered odd (ordinal 1). B:animated Selects elements from the base set B that are currently under
animated control via one of the jQuery animation methods.
B:nth-child(Xn+Y) Selects all elements from B that match the formula. X denotes
an ordinal multiplier, while Y denotes an offset. Y may be B:button Selects elements of B that are of any button type; that is:
omitted if 0. See the following examples. button, input[type=submit], input[type=reset] or
input[type=button].
B:even Selects the even elements within the set of elements
defined by B. B:checkbox Selects elements of B that are of type input[type=checkbox].

DZone, Inc. | www.dzone.com


3
jQuery Selectors
tech facts at your fingertips

jQuery Custom Selectors, continued


MATCHED SET METHODS
Syntax Description

B:enabled Selects form elements from B that are in enabled state.


While the jQuery selectors give us great flexibility in identify-
ing which DOM elements are to be added to a matched set,
B:file Selects elements of B that are of type input[type=file].
sometimes there are match criteria that cannot be expressed
B:header Selects elements from B that are of the header types:
that is <h1> through <h6>. by selectors alone. Also, given the power of jQuery method
B:hidden Selects elements of B that are hidden.
chaining, we may wish to adjust the contents of the matched
set between method invocations.
B:image Selects elements of B that are of type input[type=image].

B:input Selects form input elements from B; that is, <input>, <select>, For these situations, jQuery provides methods that operate
<textarea> and <button> elements. not upon the elements within the matched set, but on the
B:not(f) Selects elements of B that do not match the filter selector specified matched set itself. This section will summarize those methods.
by f. A filter selector is any selector beginning with : (colon), A base
set B cannot be specified as part of f.
Adding New Elements
B:parent Selects elements of B that are parents of non-empty element
children.
For adding new elements to a matched set, the add() method
is provided:
B:password Selects elements of B that are of type input[type=password].

B:radio Selects elements of B that are of type input[type=radio]. add(expression)


B:reset Selects elements of B that are of type input[type=reset] or expression (String) A selector expression that specifies the DOM elements to
button[type=reset].
be added to the matched set, or an HTML string of new elements
B:selected Selects elements of B that are in selected state. Only <option> to create and add to the set.
elements posses this state. (Element) A reference to an existing element to add.
B:submit Selects elements of B that are of type input[type=submit] or (Array) Array of references to elements to add.
button[type=submit].

B:text Selects elements of B that are of type input[type=text]. The add() method returns a new matched set that is the
B:visible Selects form elements from B that are not hidden. union of elements in the original wrapped set and any elements
either passed directly as the expression argument, or
Examples matched by the selector of the expression argument.

n $(img:animated) selects all <img> elements that are Consider:


undergoing animation $(div).add(p).css(color,red);
n $(:button:hidden) selects all button type elements This statement creates a matched set of all <div> elements,
that are hidden then creates a new matched set of the already matched <div>
n $(input[name=myRadioGroup]:radio:checked) elements and all <p> elements. The second matched sets ele-
selects all radio elements with the name attribute value of ments (all <div> and all <p> elements) are then given the CSS
myRadioGroup that are checked color property of red.

n $(:text:disabled) selects all text fields that are You may think this is not all that useful because the same could
disabled have been achieved with:
n $(#xyz p :header) selects all header type elements $(div,p).css(color,red);

within <p> elements that are within an element with an id But now consider:
value of xyz. Note the space before :header that prevents
$(div).css(font-weight,bold).add(p).
it from binding directly to the p.
css(color,red);
n $(option:not(:selected)) selects all unselected
Here the first created matched set of <div> elements is as-
<option> elements
signed a bold rendition, and then the second matched set,
n $(#myForm button:not(.someClass)) selects all with <p> elements added, is colored red.
buttons from the <form> with the id of myForm that do not
jQuery chaining (in which the css() method returns the
possess the class name someClass.
matched set) allows us to create efficient statements such as
n $(select[name=choices] :selected) selects the this one that can accomplish a great deal with little in the way
selected <option> elements within the <select> element of script.
named choices.
More Examples
n $(p:contains(coffee)) selects all <p> elements that
$(div).add(someElement).css(border,3px solid
contain the text coffee pink);
Used either separately, or in combination, the jQuery selectors $(div)
give you a great deal of power to easily create a set of elements .add([element1,element2])
that you wish to operate upon with the jQuery methods. .css(border,3px solid pink);

DZone, Inc. | www.dzone.com


4
jQuery Selectors
tech facts at your fingertips

Removing Matched Elements filter(expression)


What if we want to remove elements from the matched set? expression (String) A selector expression that specifies which elements
Thats the job of the not() method: are to be retained.
(Function) A function used to determine if an element should
not(expression) be included in the new set or not. This function is passed the
expression (String) A selector expression that specifies the DOM elements zero-based ordinal of the element within the original set, and
to be removed from the matched set. the function context (this) is set to the current element.
Returning false as the function result causes the element to
(Element) A reference to an existing element to remove.
not be included in the new set.
(Array) Array of references to elements to remove.

Like add(), this method creates and returns a new matched The filter() method can be passed either a selector expression
set, except with the elements specified by the expression (comma-separated if more than one is desired) or a function.
argument removed. The argument can be a jQuery selector, or When passed a selector, it acts like the inverse of not(),
references to elements to remove. retaining elements that match the selector (as opposed to
excluding them). When passed a function, the function is in-
Examples
voked for each element and decisions that cannot be expressed
$(body *).css(font-weight,bold)
by selectors can be made regarding the exclusion or inclusion
.not(p).css(color,red);
of each element.
Makes all body elements bold, then makes all but <p>
elements red. Examples
$(body *).css(font-weight,bold) $(.bashful).show()
.not(anElement).css(color,red); .filter(img[src$=.gif]).attr(title,Hi there!);

Similar to the previous except the element referenced by Selects all elements with class name bashful, makes sure
variable anElement is not included in the second set (and that they are visible, filters the set down to just GIF images,
therefore not colored red). and assigns a title attribute to them.
$(img[src^=images/]).filter(function(){
Avoid a typical beginners mistake and never return $(this).attr(title).match(/.+@.+\.com/)!= null;

Hot confuse the not() method, which will remove })


.hide();
Tip elements from the matched set, with the
remove() method, which will remove the Selects images from a specific folder, filters them to only
elements in the matched set from the HTML DOM! those whose title attribute matches a rudimentary .com
email address, and hides those elements.

Finding Descendants
Slicing and Dicing Matched Sets
Sometimes its useful to limit the search for elements to
Rather than matching elements by selector, we may sometimes
descendants of already identified elements. The find()
wish to slice up a matched set based upon the position of the
method does just that:
elements within the set. This section introduces two methods
find(expression) that do that for us.
expression (String) A selector expression that specifies which descendant Both of these methods assume zero-based indexing.
elements are to be matched.
slice(being,end)
Unlike the previously examined methods, find() only accepts
begin (Number) The beginning position of the first element to
a selector expression as its argument. The elements within the be included in the new set.
existing matched set will be searched for descendants that
end (Number) The end position of the first element to not be
match the expression. Any elements in the original matched included in the new set. If omitted, all elements from begin to
set that match the selector are not included in the new set. the end of the set are included.

Example Examples
$(div).css(background-color,blue)
.find(img).css(border,1px solid aqua);; $(body *).slice(2).hide();

Selects all <div> elements, makes their background blue, Selects all body elements, then creates a new set containing
selects all <img> elements that are descendants of those all but the first two elements, and hides them.
<div> elements (but not <img> elements that are not $(body *).slice(2,3).hide();
descendants) and gives them an aqua border.
Selects all body elements, then creates a new set containing
Filtering Matched Sets the third element in the set and hides it. Note that the new
When really fine-grained control is required for filtering the ele- set contains just one element: that at position 2. The element
ments of a matched set, the filter() method comes in handy: at position 3 is not included.

DZone, Inc. | www.dzone.com


5
jQuery Selectors
tech facts at your fingertips

Slicing and Dicing Matched Sets, continued For example, lets say that you wanted to collect the values of
all form elements within a form named myForm:
eq(position)
var values = $(#myForm :input).map(function(){
position (Number) The position of a single element to be included in the return $(this).val();
new set. });

The eq(n) method can be considered shorthand for


slice(n,n+1).
The map() function returns a jQuery object
Matching by Relationship Hot instance. To convert this to a normal JavaScript
Frequently we may want to create new matched sets based Tip array, you can use the get() method without
upon relationships between elements. These methods are parameters:
similar enough that well present them en masse in the var values = $(#myForm :input).map(function(){
following table: return $(this).val();
}).get();
Method Description
In this case, values references a JavaScript array rather than
children(expression) Creates a new matched set containing all unique
children of the elements in the original matched set
a jQuery wrapped object.
that match the optional expression.

next(expression) Creates a new matched set containing unique


following (next) siblings of the elements in the Controlling Chaining
original matched set that match the optional
expression. Only immediately following siblings All of the methods examined create new matched sets whose
are returned.
contents are determined in the manner explained for each
nextAll(expression) Creates a new matched set containing unique method. But what happens to the original? Is it dismissed?
following (next) siblings of the elements in the
original matched set that match the optional It is not. When a new wrapped set is created it is placed on the
expression. All following siblings are returned.
top of a stack of sets, with the top-most set being the one
parent(expression) Creates a new matched set containing unique to which any methods will be applied (as we have seen in the
immediate parents of the elements in the original
matched set that match the optional expression. examples). But jQuery allows you to pop the top-most set
off that stack so that you can apply methods to the original
parents(expression) Creates a new matched set containing all
ancestors of the elements in the original matched set. It does this with the end() method:
set that match the optional expression.
end()
prev(expression) Creates a new matched set containing unique
preceding siblings of the elements in the original (no arguments)
matched set that match the optional expression.
Only immediately preceding siblings are returned.
Consider a previous example:
prevAll(expression) Creates a new matched set containing unique
preceding siblings of the elements in the original $(div).add(p).css(color,red);
matched set that match the optional expression. All
preceding siblings are returned. As we recall, this creates a matched set of <div> elements,
siblings(expression) Creates a new matched set containing unique then creates a new set that also contains the <p> elements.
siblings of the elements in the original matched set Since this latter set is at the top of the stack when the css()
that match the optional expression.
method is called, it is the second set that is affected. Now
contents() Creates a new matched set containing all unique
consider:
children of the elements in the original matched set
including text nodes. When used on an <iframe>,
$(div).add(p).css(color,red).end().hide();
matches the content document.

After the css() method is called, the end() method pops


For all methods that accept a filtering expression, the expression
the second set off the stack exposing the original set of just
may be omitted in which case no filtering occurs.
<div> elements, which are then hidden.

Translating Elements Another useful method to affect how chaining the sets operates
There may be times that you want to translate the elements is the andSelf() method:
within a matched set to other values. jQuery provides the
andSelf()
map() method for this purpose.
(no arguments)
map(callback)

callback (Function) A callback function called for each element in the Calling andSelf() creates yet another new matched set that
matched set. The return values of the invocations are collected is the union of the top two matched sets on the stack. This can
into an array that is returned as the result of the map() method.
The current element is set as the function context (this) for
be useful for performing an action on a set, creating a new
each invocation.

DZone, Inc. | www.dzone.com


6
jQuery Selectors
tech facts at your fingertips

Controlling Chaining, continued merged, and a wide margin is applied to all <div> elements
and their <img> children.
distinct set, and then applying a method (or methods) to them
all. Consider: Between jQuery selectors and the jQuery methods that allow
$(div).css(background-color,yellow)
us to manipulate the matched sets, we can see that jQuery
.children(img).css(border,4px ridge maroon) gives us some powerful tools to select the DOM elements
.andSelf().css(margin,4em); that we can then operate upon with the many jQuery methods
All <div> elements are selected and their background set to (as well as the dozens and dozens of jQuery plugins) that are
yellow. Then, the <img> children of those <div> elements are available to us.
selected and have a border applied. Finally, the two sets are

ABOUT THE AUTHORS RECOMMENDED BOOK

Bear Bibeault jQuery in Action is a


Bear Bibeault has been writing software for over three decades, starting with a fast-paced introduction
Tic-Tac-Toe program written on a Control Data Cyber supercomputer via a 100-baud
and guide to the
teletype. He is a Software Architect and Technical Manager for a company that builds
jQuery library. It shows
and maintains a large financial web application used by the accountants that many of
the Fortune 500 companies keep in their dungeons. He also serves as a sheriff at you how to traverse
the popular JavaRanch.com. HTML documents,
Publications: jQuery in Action, Ajax in Practice, Prototype and Scriptaculous in Action (Manning) handle events, perform
Notable Projects: Sheriff at JavaRanch.com, FrontMan Web Application Controller animations, and add
Ajax to your web pages using jQuery. You
Yehuda Katz
Yehuda Katz has been involved in a number of open-source projects over the past learn how jQuery interacts with other tools
several years. In addition to being a core team member of the jQuery project, he is and how to build jQuery plugins.
also a core member of Merb, an alternative to Ruby on Rails (also written in Ruby).
He speaks about jQuery and Ruby at a number of regional conferences, and is the
JavaScript expert on the Merb team. He recently joined EngineYard working on BUY NOW
the Merb project full-time. books.dzone.com/books/
Publication: jQuery in Action (Manning) jquery-in-action
Notable Projects: Visual jQuery.com, jQuery Plugin Coordinator, Merb, DataMapper ORM
Web site: www.yehudakatz.com

Want More? Download Now. Subscribe at refcardz.com


Upcoming Refcardz: Available:
C# Published May 2008 FREE
n

n GlassFish Application Server n Windows PowerShell


n Flexible Rails: Flex 3 on Rails 2 n Dependency Injection in EJB 3
n RSS and Atom
Published April 2008
n Apache Struts 2
Spring Configuration Getting Started
Design Patterns
n
n
with Ajax
Getting Started with Eclipse GWT Style,
MS Silverlight 2
n
n
Published April 2008
Configuration
NetBeans IDE 6 Java Editor
and JSNI Reference
n

n Groovy Published April 2008

DZone, Inc.
1251 NW Maynard
ISBN-13: 978-1-934238-06-6
Cary, NC 27513
ISBN-10: 1-934238-06-6
50795
888.678.0399
The DZone Network is a group of free online services that aim to 919.678.0300
satisfy the information needs of software developers and architects.
Refcardz Feedback Welcome
From news, blogs, tutorials, source code and more, DZone offers refcardz@dzone.com
$7.95

everything technology professionals need to succeed. Sponsorship Opportunities 9 781934 238066


To quote PC magazine, DZone is a developers dream. sales@dzone.com

Copyright 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, Version 1.0
photocopying, or otherwise, without prior written permission of the publisher. Reference: jQuery in Action, Erich Gamma, Bear Bibeault and Yehuda Katz. Manning Publications, February 2008.

Potrebbero piacerti anche