Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if 'this' has a specific attribute?

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

like image 627
iWebaholic Avatar asked Mar 30 '11 14:03

iWebaholic


People also ask

How to check if an element has an attribute in JavaScript?

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.

How to check if an object has an attribute in Python?

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 ...

How do you check if an attribute exists in a string?

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.

How to get the name of an object with attributeerror?

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.


2 Answers

I will give the non-jQuery answer, just for kicks and giggles.

this.hasAttribute("foo")

Documentation: https://developer.mozilla.org/en/DOM/element.hasAttribute

like image 169
jessegavin Avatar answered Oct 24 '22 07:10

jessegavin


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
}
like image 32
Andrew Hare Avatar answered Oct 24 '22 07:10

Andrew Hare