jQuery attr() method : is used to add new attribute and their value or get value of an attribute. You can use this method for both adding attribute value and getting attribute value. This method is an important method for attribute of elements. You can dynamically create new attribute and assign to the elements with the help of attributes.
Syntax of jQuery attr method
Set and get Attribute value is explained with the example and demo below-
Get attribute Value :
To get attribute value only attribute name is needed as first parameter.
Here is syntax to get value from attribute.
$(selector).attr('attr_name');
attr_name: It is name of attribute whose value you want to access.
jQuery attr Method Example 1
Here is example of add attribute example –
Add Attr
To set attribute value add value of attribute as second parameter.
Here is syntax to get value from attribute.
$(selector).attr({Attr_name:Attr_val});
jQuery attr method Example 2
Here is example of Set attribute value example –
The above example will produce the following output where Background is added using attr method set value.