How to get an attribute value in jQuery?

To get an attribute value in jQuery is quite easy. For this, use the jQuery attr() method. The attr() method retrieves the value of the specified attribute from the first matched element.

Syntax

The basic syntax for getting an attribute value is ?

$(selector).attr(attributeName)

Where attributeName is the name of the attribute whose value you want to retrieve.

Example

You can try to run the following code to learn how to get an attribute value in jQuery ?

<html>
  <head>
    <title>jQuery Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <script>
      $(document).ready(function(){
        $("#getHeight").click(function(){
          alert($("img").attr("height"));
        });
        
        $("#getWidth").click(function(){
          alert($("img").attr("width"));
        });
        
        $("#getAlt").click(function(){
          alert($("img").attr("alt"));
        });
      });
    </script>
  </head>
  
  <body>
    <img src="/green/images/logo.png" alt="TutorialsPoint Logo" width="350" height="120"><br>
    <button id="getHeight">Get Height</button>
    <button id="getWidth">Get Width</button>
    <button id="getAlt">Get Alt Text</button>
  </body>
</html>

The output of the above code is ?

When you click "Get Height": Alert shows "120"
When you click "Get Width": Alert shows "350"
When you click "Get Alt Text": Alert shows "TutorialsPoint Logo"

Conclusion

The jQuery attr() method provides a simple way to retrieve attribute values from HTML elements. It returns the attribute value as a string, making it easy to work with element properties in your JavaScript code.

Updated on: 2026-03-13T17:47:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements