English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery attr() method

jQuery HTML/CSS Methods

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.

Syntax:

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))

Example

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:


   
Run Code

Parameter Value

ParameterDescription
attributeSpecify the attribute name
valueSpecify the value of the attribute
function(index, currentValue)Specify a function that returns the attribute value to be set
  • index-Return the index position of the element in the collection

  • currentValue-Return the current attribute value of the selected element

jQuery HTML/CSS Methods