Set multiple attributes at once with jQuery
Posted December 15th, 2009 in Javascript
This post shows how to set multiple attributes of an element with jQuery with one call to the attr() function. The example used shows how to set the src, width and height of an image element.
Set a single attribute with jQuery
Just briefly here's how to set a single attribute with jQuery, in this instance setting the "src" attribute to /images/myphoto.jpg:
$('#myimage').attr('src', '/images/myphoto.jpg');
Setting multiple attributes with jQuery
Setting multiple attributes is done the same was as setting a single attribute, but instead of passing a name and value as the two parameters to the attr() function, pass an associative array containing the attribute names and values and key-value pairs.
For example, to set the src, width and height of an image element, do this:
$('#myimage').attr({
src: '/images/myphoto.jpg',
width: 200,
height: 300
});
Note the { and } which indicate it's an associative array containing key-value pairs.
Related posts:
- jQuery Form Selectors (Friday, January 1st 2010)
- Specify multiple selectors with jQuery (Saturday, December 26th 2009)
- Loop through key value pairs from an associative array with Javascript (Friday, April 3rd 2009)
- Assigning values to associative arrays in Javascript (Sunday, December 30th 2007)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
