Tutorialsplane

jQuery attr Method


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.

Note : It will return value of first matching selector.

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 –

jQuery attr() Method get the attribute val

Try it »

Add Attr

To set attribute value add value of attribute as second parameter.

Note : Second parameter is mandatory for adding value of attribute.

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 –

jQuery attr() Method -Add Attr

Try it »

The above example will produce the following output where Background is added using attr method set value.

Jquery Tutorial

jQuery Effects

jQuery Traversing

jQuery HTML

jQuery Css

jQuery Scroll

jQuery Dimensions

jQuery Ajax