attr()

The jQuery attr() method is used to set or return attributes and values of the selected elements.

There are two usage of jQuery attr() method.

  1. To return attribute value: This method returns the value of the first matched element.
  2. To set attribute value: This method is used to set one or more attribute/value pairs of the set of matched elements.

Syntax:

To return an attribute's value:

snippet
$(selector).attr(attribute)

To set an attribute and value:

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

To set an attribute and value by using a function:

snippet
$(selector).attr(attribute,function(index,currentvalue))

To set multiple attributes and values:

snippet
$(selector).attr({attribute:value, attribute:value,...})

Parameters of jQuery attr() method

Parameter Description
Attribute This parameter is used to specify the name of the attribute.
Value This parameter is used to specify the value of the attribute.
Function (index, currentvalue) It is a parameter to specify a function that returns an attribute value to set.
  • Index: It is used to receive the index position of the element in the set.
  • Currentvalue: It is used to provide the current attribute value of selected elements.

Example of jQuery attr() method

Let's take an example to demonstrate jQuery attr() method.

snippet
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("img").attr("width", "500");
    });
});
</script>
</head>
<body>
<img src="good-morning.jpg" alt="Good Morning Friends"width="284" height="213"><br>
<button>Set the width attribute of the image</button>
</body>
</html>

Benefits of using jQuery attr() method

It provides two main benefits:

  • Convenience: When you use jQuery attr() method to get the value of the attribute of an element then it can be call directly on a jQuery object and chained to other jQuery methods.
  • Cross-browser consistency: You can get rid from inconsistently changing of attribute's value on different browsers or even on different versions of a single browser.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +