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")) { // ... }
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 .
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 .
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) { // ... }
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