jQuery attr() Method

jQuery attr() method sets attribute values or returns the attribute value of selected elements.

jQuery attr() method gets the attribute value only for the first element in the matched set of elements. Whereas attr() method sets the one or more attribute value for the all matched elements.

Syntax

This syntax return the value of an attribute,

$(selector).attr( attributeName );

This syntax set the attribute and value,

$(selector).attr( attributeName, value );

This syntax set multiple attributes and values,

$(selector).attr( {attributeName: value, attributeName: value, ...} );

This syntax returning the value to set,

$(selector).attr( attributeName, function(index, html) );
Parameter Type Description
attributeName String Required. specifies the name of the attribute.
value String
Number
Null
Optional. specifies the value of the attribute.
  • null - value specified attribute will be removed.
function(index, html) Function Optional. A function that returns the attribute value to set.
  • index - Return the index position of the element in the set as an argument.
  • html - Returns the old value of the selected element.

Examples

Here, in this example return the value of an attribute.

$(document).ready(function() {
  var title = $("p#one").attr("style");
  $("#div1").text(title);
});

Run it...   »


Here, in this example set the attribute and value.

$(document).ready(function() {
  $("button").click(function(){
    $("p").attr("style","text-align: center");
  });
});

Run it...   »


Here, in this example set multiple attributes and values.

$(document).ready(function() {
  $("button").click(function(){
    $("p").attr({style:"text-align: center", title: "First paragraph"});
  });
});

Run it...   »