In this section we’ll delve into the world of attributes and the methods jQuery offers to work with them.
Fetching attribute values
In jQuery, to get and set a value of an attribute you can use the attr() method. This is a typical peculiarity of jQuery. As you’ll often see, the same method can be used either to read or to write a value. In other words, the method can work as a getter or a setter. What action jQuery will perform depends on the number and types of the parameters passed. The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or to set attribute values onto all matched elements.
The syntax for the fetch variant of the attr() method (the method as a getter) is as follows.
Method syntax: attr | |
---|---|
attr(name) | |
Obtains the value assigned to the specified attribute for the first element in the matched 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. |
Even though you usually think of element attributes as those predefined by HTML, you can use attr() with custom attributes set through JavaScript or HTML markup. As you already saw in lesson 2, to add a custom attribute you can use the new HTML5 data-* attribute. To illustrate this, consider the following img element with a custom attribute (highlighted in bold):
<img id="my-image" src="image.gif" alt="An image" alt="A beautiful image"
data-custom="some value" />
Note that we’ve added a custom attribute, unimaginatively named data-custom, to the element. You can retrieve that attribute’s value as if it was any of the standard attributes, with
$('#my-image').attr('data-custom');
Attribute names aren’t case-sensitive in HTML, so regardless of how an attribute such as title is declared in the markup, you can access (or set, as you’ll see) attributes using any variant of case: Title, TITLE, TiTlE, and any other combinations are all equivalent. In XHTML, even though attribute names must be lowercase in the markup, you can retrieve them using any case variant.
The set variant of attr() has some handy features of its own. Let’s take a look.
Setting attribute values
There are two ways to set attributes onto selected elements with jQuery. Let’s start with the most straightforward, which allows you to set a single attribute at a time for all the elements retrieved. Its syntax is as follows.
Method syntax: attr | |
---|---|
attr(name, value) | |
Sets the named attribute to the passed value for all elements in the jQuery object. | |
Parameters | |
name | (String) The name of the attribute to be set. |
value | (String|Number|Boolean|Function) Specifies the value of the attribute. This can be any JavaScript expression that results in a value of the type specified. Unless a function is provided, any other value will be converted to a string. The function is invoked for each element in the set, passing the index of the element and the current value of the named attribute on the element. The return value of the function becomes the attribute value. |
Returns | |
The jQuery collection. |
This variant of attr(), which may seem simple at first, is actually rather sophisticated in its operation.
In its most basic form, the value parameter can be any JavaScript expression that results in a value that will be converted into a string. Things get more interesting when the value parameter is an inline function or a reference of a function. In such cases, the function is invoked for each element retrieved, with the return value of the function used as the attribute value. When the function is invoked, it’s passed two parameters: one that contains the zero-based index of the element within the set and one that contains the current value of the named attribute of the element. Additionally, the element is established as the function context (this) for the function invocation, allowing the function to tune its processing for each specific element—the main power of using functions in this way.
Consider the following statement:
$('[title]').attr('title', function(index, previousValue) {
return previousValue + ' I am element ' + index +
' and my name is ' + (this.id || 'unset');
});
This method will run through all the elements on the page having a title attribute. It’ll modify the title attribute of each element by appending to the previous value a string composed using the index of the element within the DOM and the id attribute of each specific element, if available, or the string 'unset' otherwise.
You’d use this means of specifying the attribute value whenever that value is dependent on other aspects of the element, when you need the original value to compute the new value, or whenever you have other reasons to set the values individually.
The second set variant of attr() allows you to conveniently specify multiple attributes at a time.
Method syntax: attr | |
---|---|
attr(attributes) | |
Uses the properties and values specified by the passed object to set corresponding attributes on all elements of the matched set | |
Parameters | |
attributes | (Object) An object whose properties are copied as attributes to all elements in the set |
Returns | |
The jQuery collection |
This format is a quick and easy way to set multiple attributes on all the elements of a 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 this:
$('input').attr({
value: '',
title: 'Please enter a value'
});
This statement sets the value of all input elements to the empty string and 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 similarly to the previous format of attr(); the function is invoked for each individual element in the jQuery object.
Warning
Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 6–8.
Leave a Reply