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

ADVERTISEMENT

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.

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.

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.

Conclusion

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