jQuery - Attribute method

jQuery

In this tutorial we will learn about jQuery attribute attr( ) method.

attr method

We use the attr() method to perform the following tasks.

  • Set single attribute value
  • Set multiple attribute value
  • Get the attribute value

attr - Set single attribute

To set single attribute for any given html element we pass the attribute name and value to the attr() method.

In the following example we are setting the value attribute of an input element having id sample-input1 to Hello World.

HTML

<input type="text" id="sample-input1">

jQuery

$("#sample-input1").attr("value", "Hello World");

attr - Set multiple attributes

We can also set multiple attributes by passing an object of name-value pair to the attr() method.

In the following example we are setting the value of the class attribute to awesome and value of the style attribute to color : red; for a div having id sample-div1.

jQuery

$("#sample-div1").attr({
  "class": "awesome",
  "style": "color: red;"
});

So, we will get the following changes in the div.

HTML

<div id="sample-div1" class="awesome" style="color: red;">Hello World</div>

attr: Get attribute value

To get the attribute value we just have to pass the attribute to the attr() method.

In the following example we have an image tag having src attribute and we are going to get the value of the attribute using the attr() method. The image tag has an id "sample-img1".

var src = $("#sample-img1").attr("src");

In the above code we are saving the value of the src attribute in the src variable.