jQuery attr() method
Example
Set the width attribute of the image:
$
(
"
button
"
)
.
click
(
function
(
)
{
$
(
"
img
"
)
.
attr
(
"
width
"
,
"
500
"
)
;
}
)
;
Try it »
Definition and Usage
The attr() method sets or returns the attributes and values of the selected elements.
When this method is used toReturnattribute value, it returns the value of the first matched element.
When this method is used toSettingsattribute value, it sets one or more attribute/value pairs for the matched elements.
Syntax
Returning the value of an attribute:
$(
selector
).attr(
attribute
)
Setting an attribute and value:
$(
selector
).attr(
attribute,value
)
Setting attributes and values using a function:
$(
selector
).attr(
attribute,
function(
index,currentvalue
))
Set multiple properties and values:
$(
selector
).attr({
attribute
:
value
,
attribute
:
value
,...})
| Parameters | Description |
|---|---|
| attribute | Specifies the name of the attribute. |
| value | Specifies the value of the attribute. |
| function(index,currentvalue) | Specifies a function that returns the attribute value to the collection
|
More examples
Returns the attribute value.
How to return the value of an attribute for an element.
Setting attributes and values using a function
How to use a function to set the attribute value of an element.
Setting multiple attribute/value pairs
How to set multiple attributes/values for an element.
jQuery HTML/CSS methods