English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The attr() method gets or sets the attributes and values of the selected elements.
When the attr() method is used forGetWhen setting the attribute value, it will returnThe first selected elementvalue.
When the attr() method is used forSetWhen setting the attribute value, it will beAll selected elementsSet one or more attributes/value pairs.
To remove an attribute, please useremoveAttr()Method.
Get the value of the attribute:
$(selector).attr(attribute)
Set attributes and values:
$(selector).attr(attribute, value)
Set multiple attributes and values:
$(selector).attr({attribute:value, attribute:value, ...})
Set attributes and values using a function
$(selector).attr(attribute, function(index, currentValue))
Get the value of the src attribute of the image:
$("button").click(function(){ $("img").attr("src"); });Test See‹/›
Set the src attribute of the image:
$("button").click(function(){ $("img").attr("src", "icon_jquery.png"); });Test See‹/›
Set multiple attributes and values:
$("button").click(function(){ $("img").attr({ alt: "Parrot Icon" title: "Image by Seagull", width: "350px", height: "300px" }); });Test See‹/›
Use a function to set attributes and values:
$("button").click(function(){ $("img").attr("width", function(i, val){ return val - 60; }); });Test See‹/›
Set the value of the src attribute from the drop-down list:
Parameter | Description |
---|---|
attribute | Specify the attribute name |
value | Specify the value of the attribute |
function(index, currentValue) | Specify a function that returns the attribute value to be set
|