• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / jQuery / Manipulating Element Attributes with jQuery

Manipulating Element Attributes with jQuery

19 April 2010 / Leave a Comment

Manipulating Element Attributes with jQuery

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 attributes
  • removeAttr() 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:

  1. You can add/change a single attribute for an element (or set of elements).
  2. You can add/change several attributes at once for an element (or elements) by supplying a map of attribute names and values.
  3. 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!

Filed Under: jQuery Tagged With: attr, javascript, jQuery, removeattr

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits