Latest web development tutorials

jQuery attr () method

jQuery HTML / CSS Methods jQuery HTML / CSS Methods

Examples

Setting the width property of the image:

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

try it"

Definition and Usage

attr () method sets or returns the selected element attributes and values.

When this method is used to return the property value, the first matching element is returned.

When this method is used to set the property value, compared with matching elements set one or more attribute / value pairs.


grammar

Returns the value of the property:

$(selector).attr(attribute)

The properties and values:

$(selector).attr(attribute,value)

Use the function to set the properties and values:

$(selector).attr(attribute,function(index,currentvalue))

Set multiple properties and values:

$(selector).attr({attribute:value,attribute:value,...})

参数 描述
attribute 规定属性的名称。
value 规定属性的值。
function(index,currentvalue) 规定要返回属性值到集合的函数
  • index- 接受集合中元素的 index 位置。
  • currentvalue- 接受被选元素的当前属性值。


Examples

More examples

Returns property values
How to return an element value of the property.

Use the function to set the properties and values
How to use the function to set the property value for the element.

And a plurality of attribute-value pairs
How to set multiple properties / values ​​for the elements.


jQuery HTML / CSS Methods jQuery HTML / CSS Methods