74
you pass an element or a jQuery object as the second argument to
$()
, it returns only
matching descendants of the specified element or elements. This optional second ar-
gument value defines the starting point (or points) for the query and is often called the
context.
The second way to invoke
$()
is to pass it an Element or Document or Window object.
Called like this, it simply wraps the element, document, or window in a jQuery object
and returns that object. Doing this allows you to use jQuery methods to manipulate
the element rather than using raw DOM methods. It is common to see jQuery programs
call
$(document)
or
$(this)
, for example. jQuery objects can represent more than one
element in a document, and you can also pass an array of elements to
$()
. In this case,
the returned jQuery object represents the set of elements in your array.
The third way to invoke
$()
is to pass it a string of HTML text. When you do this,
jQuery creates the HTML element or elements described by that text and then returns
a jQuery object representing those elements. jQuery does not automatically insert the
newly created elements into the document, but the jQuery methods described in
§19.3 allow you to easily insert them where you want them. Note that you cannot pass
plain text when you invoke
$()
in this way, or jQuery will think you are passing a CSS
selector. For this style of invocation, the string you pass to
$()
must include at least
one HTML tag with angle brackets.
When invoked in this third way,
$()
accepts an optional second argument. You can
pass a Document object to specify the document with which the elements are to be
associated. (If you are creating elements to be inserted into an
<iframe>
, for example,
you’ll need to explicitly specify the document object of that frame.) Or you can pass
an object as the second argument. If you do this, the object properties are assumed to
specify the names and values of HTML attributes to be set on the object. But if the
object includes properties with any of the names “css”, “html”, “text”, “width”,
“height”, “offset”, “val”, or “data”, or properties that have the same name as any of
the jQuery event handler registration methods, jQuery will invoke the method of the
same name on the newly created element and pass the property value to it. (Methods
like
css()
,
html()
, and
text()
are covered in §19.2 and event handler registration
methods are in §19.4. For example:
var img = $("<img/>", // Create a new <img> element
{ src:url, // with this HTML attribute,
css: {borderWidth:5}, // this CSS style,
click: handleClick // and this event handler.
});
Finally, the fourth way to invoke
$()
is to pass a function to it. If you do this, the function
you pass will be invoked when the document has been loaded and the DOM is ready
to be manipulated. This is the jQuery version of the
onLoad()
function from Exam-
ple 13-5. It is very common to see jQuery programs written as anonymous functions
defined within a call to
jQuery()
:
526 | Chapter 19: The jQuery Library
75
jQuery(function() { // Invoked when the document has loaded
// All jQuery code goes here
});
You’ll sometimes see
$(f)
written using the older and more verbose form:
$(document).ready(f)
.
The function you pass to
jQuery()
will be invoked with the document object as its
this
value and with the
jQuery
function as its single argument. This means that you
can undefine the global
$
function and still use that convenient alias locally with this
idiom:
jQuery.noConflict(); // Restore $ to its original state
jQuery(function($) { // Use $ as a local alias for the jQuery object
// Put all your jQuery code here
});
jQuery triggers functions registered through
$()
when the DOMContentLoaded event
is fired (§13.3.4) or, in browsers that don’t support that event, when the load event is
fired. This means that the document will be completely parsed, but that external re-
sources such as images may not be loaded yet. If you pass a function to
$()
after the
DOM is ready, that function will be invoked immediately, before
$()
returns.
The jQuery library also uses the
jQuery()
function as its namespace and defines a num-
ber of utility functions and properties under it. The
jQuery.noConflict()
function
mentioned above is one such utility function. Others include
jQuery.each()
for general-
purpose iteration and
jQuery.parseJSON()
for parsing JSON text. §19.7 lists general-
purpose utility functions, and other jQuery functions are described throughout this
chapter.
jQuery Terminology
Let’s pause here to define some important terms and phrases that you’ll see throughout
this chapter:
“the jQuery function”
The jQuery function is the value of
jQuery
or of
$
. This is the function that creates
jQuery objects, registers handlers to be invoked when the DOM is ready, and that
also serves as the jQuery namespace. I usually refer to it as
$()
. Because it serves
as a namespace, the jQuery function might also be called “the global jQuery ob-
ject,” but it is very important not to confuse it with “a jQuery object.”
“a jQuery object”
A jQuery object is an object returned by the jQuery function. A jQuery object
represents a set of document elements and can also be called a “jQuery result,” a
“jQuery set,” or a “wrapped set.”
“the selected elements”
When you pass a CSS selector to the jQuery function, it returns a jQuery object
that represents the set of document elements that match that selector. When de-
scribing the methods of the jQuery object, I’ll often use the phrase “the selected
elements” to refer to those matching elements. For example, to explain the
19.1 jQuery Basics | 527
Client-Side
JavaScript
VB.NET PDF: Basic SDK Concept of XDoc.PDF You may add PDF document protection functionality into your VB.NET program. to edit hyperlink of PDF document, including editing PDF url links and quick
clickable links in pdf from word; add email link to pdf
67
attr()
method, I might write “the
attr()
method sets HTML attributes on the
selected elements.” This is instead of a more precise but awkward description like
“the
attr()
method sets HTML attributes on the elements of the jQuery object on
which it was invoked.” Note that the word “selected” refers to the CSS selector
and has nothing to do with any selection performed by the user.
“a jQuery function”
A jQuery function is a function like
jQuery.noConflict()
that is defined in the
namespace of the jQuery function. jQuery functions might also be described as
“static methods.”
“a jQuery method”
A jQuery method is a method of a jQuery object returned by the jQuery function.
The most important part of the jQuery library is the powerful methods it defines.
The distinction between jQuery functions and methods is sometimes tricky because a
number of functions and methods have the same name. Note the differences between
these two lines of code:
// Call the jQuery function each() to
// invoke the function f once for each element of the array a
$.each(a,f);
// Call the jQuery() function to obtain a jQuery object that represents all
// <a> elements in the document. Then call the each() method of that jQuery
// object to invoke the function f once for each selected element.
$("a").each(f);
The official jQuery documentation at http://jquery.com uses names like
$.each
to refer
to jQuery functions and names like
.each
(with a period but without a dollar sign) to
refer to jQuery methods. In this book, I’ll use the terms “function” and “method”
instead. Usually it will be clear from the context which is being discussed.
19.1.2 Queries and Query Results
When you pass a CSS selector string to
$()
, it returns a jQuery object that represents
the set of matched (or “selected”) elements. CSS selectors were introduced in
§15.2.5, and you can review that section for examples—all of the examples shown
there work when passed to
$()
. The specific selector syntax supported by jQuery is
detailed in §19.8.1. Rather than focus on those advanced selector details now, however,
we’re going to first explore what you can do with the results of a query.
The value returned by
$()
is a jQuery object. jQuery objects are array-like: they have a
length
property and have numeric properties from 0 to
length
-1. (See §7.11 for more
on array-like objects.) This means that you can access the contents of the jQuery object
using standard square-bracket array notation:
$("body").length // => 1: documents have only a single body element
$("body")[0] // This the same as document.body
If you prefer not to use array notation with jQuery objects, you can use the
size()
method instead of the
length
property and the
get()
method instead of indexing with
528 | Chapter 19: The jQuery Library
101
square brackets. If you need to convert a jQuery object to a true array, call the
toArray()
method.
In addition to the
length
property, jQuery objects have three other properties that are
sometimes of interest. The
selector
property is the selector string (if any) that was used
when the jQuery object was created. The
context
property is the context object that
was passed as the second argument to
$()
, or the Document object otherwise. Finally,
all jQuery objects have a property named
jquery
, and testing for the existence of this
property is a simple way to distinguish jQuery objects from other array-like objects.
The value of the
jquery
property is the jQuery version number as a string:
// Find all <script> elements in the document body
var bodyscripts = $("script", document.body);
bodyscripts.selector // => "script"
bodyscripts.context // => document.body
bodyscripts.jquery // => "1.4.2"
$() versus querySelectorAll()
The
$()
function is similar to the Document method
querySelectorAll()
that was de-
scribed in §15.2.5: both take a CSS selector as their argument and return an array-like
object that holds the elements that match the selector. The jQuery implementation uses
querySelectorAll()
in browsers that support it, but there are good reasons to use
$()
instead of
querySelectorAll()
in your own code:
•
querySelectorAll()
has only recently been implemented by browser vendors.
$()
works in older browsers as well as new ones.
• Because jQuery can perform selections “by hand,” the CSS3 selectors supported
by
$()
work in all browsers, not just those browsers that support CSS3.
• The array-like object returned by
$()
(a jQuery object) is much more useful than
the array-like object (a NodeList) returned by
querySelectorAll()
.
If you want to loop over all elements in a jQuery object, you can call the
each()
method
instead of writing a
for
loop. The
each()
method is something like the ECMAScript 5
(ES5)
forEach()
array method. It expects a callback function as its sole argument, and
it invokes that callback function once for each element in the jQuery object (in docu-
ment order). The callback is invoked as a method of the matched element, so within
the callback the
this
keyword refers to an Element object.
each()
also passes the index
and the element as the first and second arguments to the callback. Note that
this
and
the second argument are raw document elements, not jQuery objects; if you want to
use a jQuery method to manipulate the element, you’ll need to pass it to
$()
first.
jQuery’s
each()
method has one feature that is quite different than
forEach()
: if your
callback returns
false
for any element, iteration is terminated after that element (this
is like using the
break
keyword in a normal loop).
each()
returns the jQuery object on
which it is called, so that it can be used in method chains. Here is an example (it uses
the
prepend()
method that will be explained in §19.3):
19.1 jQuery Basics | 529
Client-Side
JavaScript
78
// Number the divs of the document, up to and including div#last
$("div").each(function(idx) { // find all <div>s, and iterate through them
$(this).prepend(idx + ": "); // Insert index at start of each
if (this.id === "last") return false; // Stop at element #last
});
Despite the power of the
each()
method, it is not very commonly used, since jQuery
methods usually iterate implicitly over the set of matched elements and operate on them
all. You typically only need to use
each()
if you need to manipulate the matched ele-
ments in different ways. Even then, you may not need to call
each()
, since a number
of jQuery methods allow you to pass a callback function.
The jQuery library predates the ES5 array methods, and it defines a couple of other
methods that provide functionality similar to the ES5 methods. The jQuery method
map()
works much like the
Array.map()
method. It accepts a callback function as its
argument and invokes that function once for each element of the jQuery object, col-
lecting the return values of those invocations, and returning a new jQuery object hold-
ing those return values.
map()
invokes the callback in the same way that the
each()
method does: the element is passed as the
this
value and as the second argument and
the index of the element is passed as the first argument. If the callback returns
null
or
undefined
, that value is ignored and nothing is added to the new jQuery object for that
invocation. If the callback returns an array or an array-like object (such as a jQuery
object), it is “flattened” and its elements are added individually to the new jQuery
object. Note that the jQuery object returned by
map()
may not hold document elements,
but it still works as an array-like object. Here is an example:
// Find all headings, map to their ids, convert to a true array, and sort it.
$(":header").map(function() { return this.id; }).toArray().sort();
Along with
each()
and
map()
, another fundamental jQuery method is
index()
. This
method expects an element as its argument and returns the index of that element in
the jQuery object, or –1 if it is not found. In typical jQuery fashion, however, this
index()
method is overloaded. If you pass a jQuery object as the argument,
index()
searches for the first element of that object. If you pass a string,
index()
uses it as a CSS
selector and returns the index of the first element of this jQuery object in the set of
elements matching that selector. And if you pass no argument,
index()
returns the index
of the first element of this jQuery object within its sibling elements.
The final general-purpose jQuery method we’ll discuss here is
is()
. It takes a selector
as its argument and returns
true
if at least one of the selected elements also matches
the specified selector. You might use it in an
each()
callback function, for example:
$("div").each(function() { // For each <div> element
if ($(this).is(":hidden")) return; // Skip hidden elements
// Do something with the visible ones here
});
530 | Chapter 19: The jQuery Library
53
19.2 jQuery Getters and Setters
Some of the simplest, and most common, operations on jQuery objects are those that
get or set the value of HTML attributes, CSS styles, element content, or element
geometry. This section describes those methods. First, however, it is worth making
some generalizations about getter and setter methods in jQuery:
• Rather than defining a pair of methods, jQuery uses a single method as both getter
and setter. If you pass a new value to the method, it sets that value; if you don’t
specify a value, it returns the current value.
• When used as setters, these methods set values on every element in the jQuery
object, and then return the jQuery object to allow method chaining.
• When used as getters, these methods query only the first element of the set of
elements and return a single value. (Use
map()
if you want to query all elements.)
Since getters do not return the jQuery object they are invoked on, they can only
appear at the end of a method chain.
• When used as setters, these methods often accept object arguments. In this case,
each property of the object specifies a name and a value to be set.
• When used as setters, these methods often accept functions as values. In this case,
the function is invoked to compute the value to be set. The element that the value
is being computed for is the
this
value, the element index is passed as the first
argument to the function, and the current value is passed as the second argument.
Keep these generalizations about getters and setters in mind as you read the rest of this
section. Each subsection below explains an important category of jQuery getter/setter
methods.
19.2.1 Getting and Setting HTML Attributes
The
attr()
method is the jQuery getter/setter for HTML attributes, and it adheres to
each of the generalizations described above.
attr()
handles browser incompatibilities
and special cases and allows you to use either HTML attribute names or their JavaScript
property equivalents (where they differ). For example, you can use either “for” or
“htmlFor” and either “class” or “className”.
removeAttr()
is a related function that
completely removes an attribute from all selected elements. Here are some examples:
$("form").attr("action"); // Query the action attr of 1st form
$("#icon").attr("src", "icon.gif"); // Set the src attribute
$("#banner").attr({src:"banner.gif", // Set 4 attributes at once
alt:"Advertisement",
width:720, height:64});
$("a").attr("target", "_blank"); // Make all links load in new windows
$("a").attr("target", function() { // Load local links locally and load
if (this.host == location.host) return "_self"
else return "_blank"; // off-site links in a new window
});
19.2 jQuery Getters and Setters | 531
Client-Side
JavaScript
75
$("a").attr({target: function() {...}}); // We can also pass functions like this
$("a").removeAttr("target"); // Make all links load in this window
19.2.2 Getting and Setting CSS Attributes
The
css()
method is very much like the
attr()
method, but it works with the CSS styles
of an element rather than the HTML attributes of the element. When querying style
values,
css()
returns the current (or “computed”; see §16.4) style of the element: the
returned value may come from the
style
attribute or from a stylesheet. Note that it is
not possible to query compound styles such as “font” or “margin”. You must instead
query individual styles such as “font-weight”, “font-family”, “margin-top”, or “margin-
left”. When setting styles, the
css()
method simply adds the style to the element’s
style
attribute.
css()
allows you to use hyphenated CSS style names (“background-
color”) or camel-case JavaScript style names (“backgroundColor”). When querying
style values,
css()
returns numeric values as strings, with units suffixes included. When
setting, however, it converts numbers to strings and adds a “px” (pixels) suffix to them
when necessary:
$("h1").css("font-weight"); // Get font weight of first <h1>
$("h1").css("fontWeight"); // Camel case works, too
$("h1").css("font"); // Error: can't query compound styles
$("h1").css("font-variant", // Set a style on all <h1> elements
"smallcaps");
$("div.note").css("border", // Okay to set compound styles
"solid black 2px");
$("h1").css({ backgroundColor: "black", // Set multiple styles at once
textColor: "white", // camelCase names work better
fontVariant: "small-caps", // as object properties
padding: "10px 2px 4px 20px",
border: "dotted black 4px" });
// Increase all <h1> font sizes by 25%
$("h1").css("font-size", function(i,curval) {
return Math.round(1.25*parseInt(curval));
});
19.2.3 Getting and Setting CSS Classes
Recall that the value of the
class
attribute (accessed via the
className
property in Java-
Script) is interpreted as a space-separated list of CSS class names. Usually, we want to
add, remove, or test for the presence of a single name in the list rather than replacing
one list of classes with another. For this reason, jQuery defines convenience methods
for working with the
class
attribute.
addClass()
and
removeClass()
add and remove
classes from the selected elements.
toggleClass()
adds classes to elements that don’t
already have them and removes classes from those that do.
hasClass()
tests for the
presence of a specified class. Here are some examples:
// Adding CSS classes
$("h1").addClass("hilite"); // Add a class to all <h1> elements
$("h1+p").addClass("hilite first"); // Add 2 classes to <p> elts after <h1>
$("section").addClass(function(n) { // Pass a function to add a custom class
return "section" + n; // to each matched element
532 | Chapter 19: The jQuery Library
Documents you may be interested
Documents you may be interested