jQuery in Action
Manipulating element properties and attributes
55
as the
this
variable for the function invocation, allowing the function to tune
its processing for each specific element--the main power of using functions in
this way.
this way.
Consider the following statement:
$('*').attr('title',function(index) {
return 'I am element ' + index + ' and my name is ' +
(this.id ? this.id : 'unset');
});
This command will run through all elements on the page, setting the
title
attribute of each element to a string composed using the index of the element
within the
within the
DOM
and the
id
attribute of each specific element.
We'd use this means of specifying the attribute value whenever that value is
dependent upon other aspects of the elements, rather than some unrelated value.
The second set variant of
attr()
allows us to conveniently specify multiple
attributes at a time.
This format is a quick and easy way to set multiple attributes onto all the elements
of a wrapped set. The passed parameter can be any object reference, commonly
an object literal, whose properties specify the names and values of the attributes
to be set. Consider:
of a wrapped set. The passed parameter can be any object reference, commonly
an object literal, whose properties specify the names and values of the attributes
to be set. Consider:
$('input').attr(
{ value: '', title: 'Please enter a value' }
);
This statement sets the
value
of all
<input>
elements to the empty string, as well
as sets the
title
to the string
Please enter a value
.
Note that if any property value in the object passed as the
value
parameter is
a function reference, it operates in a manner similar to that described for the
Command syntax: attr
attr(attributes)
Sets the attributes and values specified by the passed object onto all elements of the
matched set
matched set
Parameters
attributes
(Object) An object whose properties are copied as attributes to all
elements in the wrapped set
Returns
The wrapped set
The wrapped set