Introduction:

Here we are going to explain what is attr() method or how to use attr() method or why use attr() method or how to set or return attributes and values of the selected elements t in jQuery with example.

Description: 

The jQuery attr() method is used to set or return attributes and values of the selected html elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

 Syntax:

To return an attribute's value:

$(selector).attr(attribute)

 

To set an attribute and value:

 

$(selector).attr(attribute,value)  

 

 

  • Example of jQuery empty() method


Let's see an example to of jQuery attr() method.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jquery attr() tutorial</title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("button").click(function () {
                $("input").attr("value", "Aditya Kumar patel");
            });
        });
    </script>
 
</head>
<body>
    
    <input type="text" /> 
    <button>set attribute</button>
</body>
</html>

 

As shown in the above program, when user click on button then add value attribute in text box.

Output:

use jQuery attr() method

     I hope it will help to you.

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like