Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hasAttr checking to see if there is an attribute on an element [duplicate]

Tags:

jquery

How do you check if there is an attribute on an element in jQuery? Similar to hasClass, but with attr?

For example,

if ($(this).hasAttr("name")) {     // ... } 
like image 253
Mark Avatar asked Aug 23 '09 08:08

Mark


People also ask

How do you know if an element has attr?

To check if an HTML element has any attributes, you can use the hasAttributes() method. This method returns true if the specified node has any attributes, otherwise false . If the specified node is not an Element node, for example, whitespace and comments, the return value is always false .

How do you check if an element has an attribute in Javascript?

The hasAttribute() returns a Boolean value that indicates if the element has the specified attribute. If the element contains an attribute, the hasAttribute() returns true; otherwise, it returns false .


1 Answers

var attr = $(this).attr('name');  // For some browsers, `attr` is undefined; for others, // `attr` is false.  Check for both. if (typeof attr !== 'undefined' && attr !== false) {     // ... } 
like image 188
strager Avatar answered Sep 20 '22 00:09

strager