I want to check if the element I click (this) has a specific attribute, as a condition in the if clause. Is it possible to do this with JavaScript or jQuery?
Thanks
Summary: in this tutorial, you will learn how to use the JavaScript hasAttribute () to check if an element has an attribute. To check an element has a specified attribute or not, you use the hasAttribute () method: The hasAttribute () method accepts an argument that specifies the name of the attribute that you want to check.
There're two ways to check if a Python object has an attribute or not. The first way is to call the built-in function hasattr (object, name), which returns True if the string name is the name of one of the object 's attributes, False if not. The second way is to try to access an attribute in an object and perform some other function ...
Using hasAttribute () Function in JavaScript JavaScript has a hasAttribute () function which can be used to test whether an attribute exists on an element or not. It returns a boolean true if a match is found and a boolean false when no match is found.
The first way is to call the built-in function hasattr(object, name), which returns True if the string name is the name of one of the object's attributes, False if not. The second way is to try to access an attribute in an object and perform some other function if an AttributeError was raised.
I will give the non-jQuery answer, just for kicks and giggles.
this.hasAttribute("foo")
Documentation: https://developer.mozilla.org/en/DOM/element.hasAttribute
In JavaScript, anything that is null
or undefined
(or even an empty string) is implicitly "false" so you can do this (assuming that you were referring to a HTML attribute using jQuery):
if ($(this).attr('foo')) {
}
Also, if you need the value from the attribute you can do this:
var foo;
if (foo = $(this).attr('foo')) {
// use "foo" in here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With