In Accessing Element Content with jQuery, you learned how to use jQuery to read and change the contents of HTML elements. This tutorial concentrates on reading and changing element attributes.
Attributes are the name/value pairs that you assign to elements in their start tags. Here are some examples (the attribute names and values are in bold):
<a href="http://www.elated.com/">Elated</a>
<p title="Introduction">Here's some intro text</p>
<img src="myphoto.jpg" alt="My Photo" width="300" height="300" />
<div class="summary">Here's a summary</div>
jQuery lets you read, add, change, or remove any attribute within an element. To do these things, you use the following methods:
attr()
to read, add, and change attributesremoveAttr()
to remove attributes
In this tutorial you’ll learn how to use both attr()
and removeAttr()
to work with attributes.
Although you can use attr()
and removeAttr()
with any attributes, there are special jQuery methods for working specifically with class
attributes. This is partly because you tend to work with CSS classes a lot with jQuery, and partly because class
attribute values often contain multiple class names, making them more complex than most other attributes.
If you want to work with form field values, take a look at the val()
method. Not only does val()
provide an easy way to work with value
attributes, but it can also read and set selected items in a select
list, and more besides.
Reading attribute values
Reading the value of an element’s attribute is easy. Just call the attr()
method on the jQuery object that contains the element, passing in the name of the attribute to read. The method then returns the attribute value:
// Display the value of the #myLink element's 'href' attribute
alert ( $('a#myLink').attr('href') );
If your jQuery object contains multiple elements, attr()
only reads the attribute from the first element in the set.
Setting attribute values
You can also use attr()
to add attributes or change attribute values, as follows:
- If the attribute doesn’t exist in the element, it is added and given the specified value.
- If the attribute already exists, its value is updated with the specified value.
There are 3 ways you can use attr()
to add or change attributes:
- You can add/change a single attribute for an element (or set of elements).
- You can add/change several attributes at once for an element (or elements) by supplying a map of attribute names and values.
- You can dynamically add/change a single attribute across many elements at once by creating a callback function.
Setting a single attribute
To add or change a single attribute in an element, call attr()
with the attribute name and value. For example:
// Change the #myLink element's 'href' attribute to 'http://www.example.com/'
// (if the "href" attribute doesn't exist, it is created automatically)
$('a#myLink').attr('href', 'http://www.example.com/');
You can set the same attribute across multiple elements too:
// Change all links to point to 'http://www.example.com/'
$('a').attr('href', 'http://www.example.com/');
Setting multiple attributes using a map
You can set several attributes for 1 or more elements at the same time by using a map — that is, a list of name/value pairs. Maps look like this:
{
name1: value1,
name2: value2,
...
}
The following example sets 2 attributes for an img
element at once:
// Set the 'src' and 'alt' attributes for the #myPhoto img element
$('img#myPhoto').attr({
'src': 'mypic.jpg',
'alt': 'My Photo'
});
Again, you can set multiple attributes across a bunch of elements too:
// Set the 'src' and 'alt' attributes for all img elements
$('img').attr({
'src': 'mypic.jpg',
'alt': 'My Photo'
});
Setting an attribute using a callback function
Instead of passing an attribute value to attr()
, you can pass the name of a callback function. This lets you dynamically set attribute values on many elements at once, based on each element’s position, existing attribute value, or other properties.
Your callback function should accept the following 2 arguments:
- The index position of the current element in the set (starting from zero)
- The old value of the attribute (if any) for the current element
The return value of the function is then used as the replacement attribute value.
As well as accessing the current element position and old attribute value, your function can access the current element itself using the this
keyword. This means you can access any property or method of each element from within your function.
Here’s a complete example that uses a callback function to add an alt
attribute to each image in the page, based on the image’s position and its src
attribute:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$( init );
function init() {
// Set the 'alt' attribute for all 'img' elements
$('img').attr( 'alt', setAltText );
function setAltText( index, attributeValue ) {
return ( 'Image ' + (index+1) + ': ' + this.src );
}
}
</script>
</head>
<body>
<img src="myphoto.jpg"/>
<img src="yourphoto.jpg"/>
</body>
</html>
After running the above code, the first image has an alt
attribute value of "Image 1: myphoto.jpg"
, and the second image has an alt
attribute value of "Image 2: yourphoto.jpg"
.
Removing attributes
To remove an attribute from an element, call removeAttr()
, passing in the name of the attribute to remove. Here’s an example:
// Remove the 'title' attribute from the #myLink element
$('a#myLink').removeAttr('title');
You can also call removeAttr()
on a jQuery object containing multiple elements. removeAttr()
then removes the specified attribute from all of those elements:
// Remove the 'title' attribute from all links
$('a').removeAttr('title');
Summary
In this article you’ve looked at how to work with element attributes in jQuery. You’ve seen how to:
- Read attribute values
- Set a single attribute
- Set different attributes at the same time
- Use a callback function to dynamically set an attribute’s value across a set of elements, and
- Remove attributes from an element
In the next tutorial you learn how to use the jQuery hasClass()
, addClass()
, removeClass()
and toggleClass()
methods to work specifically with class
attributes.
Happy coding!
Leave a Reply