Quick Tip – Reading & Editing HTML Attributes in jQuery

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.

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.

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.

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:

I’d be interested to hear your ideas or questions below.

Posted Monday, July 20th, 2009 · Back to Top

SPONSOR

Add Comment

4 Comments 13 Mentions

  1. Montana Flynn Author Editor

    great breakdown of .attr, I would like to see more posts like these.
    .-= Montana Flynn´s last blog ..Twitter’s new homepage design =-.

    ·

  2. Daniel H Pavey Author Editor

    Really helpful post, thanks

    As a bit of a jQuery beginner I would also like to see more like these!!

    ·

  3. Mujahid Author Editor

    Great tutorial, thanks :)

    ·

  4. Jarod Online Author Editor

    Great job. I’ve been wondering what the attr was for, for a long time until now

    ·

 

Build Internet by One Mighty Roar. Since 2008.