Set multiple attributes at once with jQuerySet 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:

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.

Comments

blog comments powered by Disqus