jQuery Attribute Operation - attr() Method

Example

Change the width attribute of the image:

$("button").click(function(){
  $("img").attr("width","180");
});

Try it yourself

Definition and Usage

The attr() method sets or returns the attribute value of the selected element.

Depending on the different parameters of this method, its working mode may also vary.

Return attribute value

Return the attribute value of the selected element.

Syntax

$(selector).attr(attribute)
Parameters Description
attribute Specify the attribute to get its value.

Try it yourself

Set attribute/value

Set the attributes and values of the selected elements.

Syntax

$(selector).attr(attribute,value)
Parameters Description
attribute Specify the name of the attribute.
value Specify the value of the attribute.

Try it yourself

Use a function to set attribute/value

Set the attributes and values of the selected elements.

Syntax

$(selector).attr(attribute,function(index,oldvalue))
Parameters Description
attribute Specify the name of the attribute.
function(index,oldvalue)

Specify a function to define the returned attribute value.

This function can accept and use the index value of the selector and the current attribute value.

Try it yourself

Set multiple attribute/value pairs

Set one or more attributes and values for the selected elements.

Syntax

$(selector).attr({attribute:value, attribute:value ...})
Parameters Description
attribute:value Specify one or more attribute/value pairs.

Try it yourself