In this tutorial we will learn about jQuery attribute attr() method.
We use the attr() method to perform the following tasks.
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.
<input type="text" id="sample-input1">
$("#sample-input1").attr("value", "Hello World");
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.
color : red;
"style": "color: red;"
So, we will get the following changes in the div.
<div id="sample-div1" class="awesome" style="color: red;">Hello World</div>
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.
Copyright © 2014 - 2017 DYclassroom. All rights reserved.
rendered in 0.0388 sec