Home / Set multiple attributes at once with jQuery

Set multiple attributes at once with jQuery

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.