jQuery attr

jQuery attr() method is used to set or get the attribute value(s) of HTML DOM Element.

In this tutorial, you will learn about jQuery attr() method, its syntax and usage, with examples.

Syntax jQuery attr

Following is the syntax to use jQuery attr() method

Get Attribute Value

To get the attribute value of selected HTML Element,

$("htmlElement").attr("attribute_key");

Set Attribute Value

To set the attribute value of selected HTML Element,

$("htmlElement").attr("attribute_key");

Set Multiple Attribute Values

To set multiple attribute values for a selected HTML Element,

$("htmlElement").attr({
	"attribute_key1": "value1",
	"attribute_key2": "value2",
	"attribute_key3": "value3"
});

Examples jQuery attr

Following examples help you understand the usage of jQuery attr() method :

1 Example Get attribute value of HTML Element

In the following example, upon clicking the button, we shall read the href of anchor link with id=”atk” and display it using alert.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#show").click(function(){
    alert($("#atk").attr("href"));
  });
});
</script>
</head>
<body>

 <a href="https://www.tutorialkart.com/" id="atk">Tutorial Kart</a><br>

 <button id="show">Display href of the anchor link</button>

</body>
</html>

2 Example Set attribute value of HTML Element

In the following example, upon clicking the button, we shall set a value to the href attribute of anchor link.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#show").click(function(){
    $("#atk").attr("href","https://www.tutorialkart.com/");
  });
});
</script>
</head>
<body>

 <a id="atk">Tutorial Kart</a><br>

 <button id="show">Set value to href of the anchor link</button>

</body>
</html>

3 Example Set multiple attribute values

In the following example, learn to use jQuery attr() method, to set multiple attribute values in a single statement.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#show").click(function(){
    $("#atk").attr({
      "href" : "https://www.tutorialkart.com/",
      "title" : "Learn jQuery with Tutorial Kart"
    });
  });
});
</script>
</head>
<body>

  <a id="atk">Tutorial Kart</a><br>

  <button id="show">Set href and title for the anchor link</button>

</body>
</html>

Conclusion

In this jQuery Tutorial, we have learnt jQuery attr() method : Syntax and Usage with examples.