Quick Tip – Reading & Editing HTML Attributes in jQuery
jQuery Attributes allow for some interesting editing to happen once a page has already loaded. HTML attributes that had to remain static at one time can now be adjusted with just a few lines of code. This tutorial will be focusing on one in particular – attr.
A Sampling of Potential Uses
Captions based on ‘alt’ or ‘title’ attributes
Let’s say that one day you wake up and get inspired to craft a jQuery powered image slideshow. You’ve got your images working but now you’re interested in including captions for each one as they cycle through, if only there was some way to pull the caption from the ‘title’ or ‘alt’ tag within the ‘img’ tag. Be still my little developer, that’s what the jQuery attr is for.
$('.caption').html(
$('.imageslide').attr('title')
);
It looks simple because it is, essentially all we are doing is using the ‘.html’ to make the contents of ‘.caption’ ( <div class=”caption”>This is our target area</div>) the same as the ‘title’ attribute of ‘.imageslide’.
Swap images using ‘src’ attribute
Since we can use jQuery to make changes to the page on the fly, we can use ‘attr’ to swap images on events such as hover.
$('.theimage').hover(function(){//When hover starts
$(this).attr('src','alternate.jpg');
},
function(){ //When hover ends
$(this).attr('src','main.jpg');
});
If you followed along, when the image is hovered over, the image is swapped via ‘src’. Please note that the first part of attr() defines which attribute we’re dealing with and the second establishes what the value is.
Changing multiple attributes at once
Only editing a single attribute at a time could result in a lot of repetitive code, but luckily you update more than one at a time, how convenient.
$('.theimage').click(function(){
$(this).attr({
src: 'alternate.jpg',
title: 'Alternate State'
});
});
The List Goes On
Obviously there a quite a few potential uses, which is where the brainstorming comes in. We’ve used ‘attr’ to edit in a few other tutorials for those interested in practical applications:
- Quick Tip – Resizing Images Based On Browser Window Size (Image Swapping)
- Supersized Plugin (Captions from Image)
- Create a Content Rich Tooltip with JSON and jQuery (Image Swapping)
I’d be interested to hear your ideas or questions below.



