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
How do I find a certain attribute exists or not for a selected item in jQuery?
To find a certain attribute exists or not for a selected item in jQuery, you have several methods available. The most common approaches are using the native JavaScript hasAttribute() method or jQuery's attr() method to check for attribute existence.
Method 1: Using hasAttribute() Method
The hasAttribute() method is a native JavaScript method that returns true if the specified attribute exists on the element, and false otherwise.
Example
You can try to run the following code to learn how to find a certain attribute exists or not ?
<!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').on('click', function() {
if (this.hasAttribute("myattr")) {
alert('True - myattr attribute exists');
} else {
alert('False - myattr attribute does not exist');
}
});
});
</script>
</head>
<body>
<button class='button' style='color: green' myattr='demo'>
Button One
</button>
<button class='button'>
Button Two
</button>
</body>
</html>
Method 2: Using jQuery attr() Method
Alternatively, you can use jQuery's attr() method to check if an attribute exists by verifying if it returns undefined ?
$(document).ready(function(){
$('button').on('click', function() {
if ($(this).attr("myattr") !== undefined) {
alert('True - myattr attribute exists');
} else {
alert('False - myattr attribute does not exist');
}
});
});
Conclusion
Both methods effectively check for attribute existence in jQuery, with hasAttribute() being more direct and attr() providing additional jQuery functionality for attribute manipulation.
