jQuery attr() Method

The jQuery attr() method is used to return or set the attributes and values of the selected elements. When you have to get the value of the attributes of an element, you can use this method. You can also use this method when you have to set the attribute with its value.

jQuery :attr() Method

Let’s set and get the attributes and values of the elements with the examples given below.

jQuery attr() Method to Return Attribute Value

The jQuery attr() method can be used to return the value of the elements. First, select the elements and then after get any attribute value.

See the syntax of the method to return the attributes and values.

Syntax

Syntax
$(selector).attr(attribute)

The below example contains the paragraph with the style attribute. You can return the value of style attribute using the example given below.

Example

Test it Live

Output


This is my paragraph.

Click the button given above to get the value of the style attribute. The method returns the value of the attribute and displays it in the alert box.

Set Attribute and Value Using jQuery attr() Method

When you want to set the attributes and values, you have to use this method. The syntax of the method is given below. It adds a single attribute with its value.

Syntax

Syntax
$(selector).attr(attribute, value)

Let’s set the style attribute with its single value in the example below. This adds a single attribute with its relevant value.

Example

Test it Live

Output


This is my paragraph.

When you click the button given above, it applies a background yellow color to the paragraph.

How to Set Multiple Attributes and Their Values

If you want to set multiple attributes and values, you can also use jQuery attr() method. You can set as many attributes as you want with its values.

Use the syntax given below to set the multiple attributes and values

Syntax

Syntax
$(selector).attr({attribute1:value1, attribute2:value2,…})

Its useful to set multiple attributes and value at one go. You have to use the example given below.

Example

Test it Live

Output



The above example contains the button and the input box. Suppose that you have to add a placeholder and background color. For this, you have to add placeholder and style attributes with its values.

You have to click the above button to add multiple attributes to the input box. After you click the button, a placeholder and background yellow color get added to the input box.

I hope you like this tutorial on jQuery attr() method. If you have any queries regarding the tutorial, please comment below.

References