jQuery in Action
54
CHAPTER 3
Bringing pages to life with jQuery
In addition to these helpful shortcuts, the set variant of
attr()
has some of its
own handy features. Let's take a look.
3.1.3 Setting attribute values
There are two ways to set attributes onto elements in the wrapped set with jQuery.
Let's start with the most straightforward that allows us set a single attribute at a
time (for all elements in the wrapped set). Its syntax is as follows:
Let's start with the most straightforward that allows us set a single attribute at a
time (for all elements in the wrapped set). Its syntax is as follows:
This variant of
attr()
, which may at first seem simple, is rather sophisticated in
its operation.
In its most basic form, when the
value
parameter is any JavaScript expression
that results in a value (including an array), the computed value of the expres-
sion is set as the attribute value.
sion is set as the attribute value.
Things get more interesting when the
value
parameter is a function refer-
ence. In such cases, the function is invoked for each element in the wrapped set,
with the return value of the function used as the attribute value. When the func-
tion is invoked, it's passed a single parameter that contains the zero-based index
of the element within the wrapped set. Additionally, the element is established
with the return value of the function used as the attribute value. When the func-
tion is invoked, it's passed a single parameter that contains the zero-based index
of the element within the wrapped set. Additionally, the element is established
maxlength
maxLength
readonly
readOnly
styleFloat
styleFloat
for IE, cssFloat for others (when used with .css)
Table 3.1 jQuery
attr()
normalized-access names (continued)
Normalized name
Source name
Command syntax: attr
attr(name,value)
Sets the named attribute onto all elements in the wrapped set using the passed value.
Parameters
name
(String) The name of the attribute to be set.
value
(String|Object|Function) Specifies the value of the attribute. This can be any Java-
Script expression that results in a value, or it can be a function. See the following
discussion for how this parameter is handled.
Script expression that results in a value, or it can be a function. See the following
discussion for how this parameter is handled.
Returns
The wrapped set.
The wrapped set.