How to get attribute of an element when using the 'click' event in jQuery?

To get attribute of an element, use the attr() method in jQuery. The attr() method retrieves the value of an attribute from the first element in the matched set of elements. When used with click events, it allows you to dynamically access element attributes when user interactions occur.

Example

You can try to run the following code to get attribute of an element using the 'click' event ?

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $("button").click(function(){
            alert("Width of image: " + $("img").attr("width"));
         });
      });
   </script>
</head>
<body>
   <img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="284" height="280"><br>
   <button>Get Width</button>
</body>
</html>

The output of the above code is ?

When you click the "Get Width" button, an alert box will display:
"Width of image: 284"

Getting Multiple Attributes

You can also retrieve multiple attributes or use this to get attributes of the clicked element ?

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $("img").click(function(){
            var width = $(this).attr("width");
            var height = $(this).attr("height");
            var alt = $(this).attr("alt");
            alert("Width: " + width + ", Height: " + height + ", Alt: " + alt);
         });
      });
   </script>
</head>
<body>
   <img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="284" height="280">
   <p>Click on the image to get its attributes</p>
</body>
</html>

Conclusion

The attr() method combined with click events provides an effective way to retrieve element attributes dynamically. Using $(this) within event handlers allows you to target the specific clicked element's attributes.

Updated on: 2026-03-13T19:01:49+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements