jQuery in Action
52
CHAPTER 3
Bringing pages to life with jQuery
Similarly, we can collect all values for a specific property into an array using
each()
, as follows:
var allAlts = new Array();
$('img').each(function(){
allAlts.push(this.alt);
});
If all we want to do is obtain the property value of a single element, remember
that the matched set can be treated like a JavaScript array; we could obtain the
property via
that the matched set can be treated like a JavaScript array; we could obtain the
property via
var altValue = $('#myImage')[0].alt;
Dealing with attributes is a little less straightforward than dealing with properties
in JavaScript, so jQuery provides assistance for dealing with them. Let's look
at how.
in JavaScript, so jQuery provides assistance for dealing with them. Let's look
at how.
3.1.2 Fetching attribute values
As we'll find is true with many jQuery commands, the
attr()
command can be
used either as a read or as a write operation. When jQuery commands can per-
form such disparate operations, the number and types of parameters passed into
the command determine the variant of the command used.
form such disparate operations, the number and types of parameters passed into
the command determine the variant of the command used.
The
attr()
command can be used to either fetch the value of an attribute
from the first element in the matched set or set attribute values onto all
matched elements.
matched elements.
The syntax for the fetch variant of the
attr()
command is as follows:
Even though we usually think of attributes as predefined by
HTML
, we can use
attr()
with custom attributes set through JavaScript or
HTML
markup. To illustrate
Command syntax: attr
attr(name)
Obtains the values assigned to the specified attribute for the first element in the matched
set.
set.
Parameters
name
(String) The name of the attribute whose value is to be fetched.
Returns
The value of the attribute for the first matched element. The value undefined is returned if
the matched set is empty or the attribute doesn't exist on the first element.
The value of the attribute for the first matched element. The value undefined is returned if
the matched set is empty or the attribute doesn't exist on the first element.