Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
