794

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")) {
    // ...
}
Community
  • 1
  • 1
Mark
  • 32,293
  • 33
  • 107
  • 137
  • 14
    quickie: `if( $(this).is('[ATTRIBUTE_NAME]') ) { /* ... */ }` **BTW:** this is not a duplicate of that question anymore, is just a similar question regarding different problem, the linked duplicate is now called "Select elements by attribute" – jave.web Jul 09 '15 at 20:01
  • jQuery has no .hasAttr() function, but it is easy to implement: jQuery.prototype.hasAttr = function(attribute) { var a = $(this).attr(attribute); return ((typeof a !== "undefined") && (a !== false)); }; – Spider IT Sep 04 '22 at 10:05

9 Answers9

1247
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) {
    // ...
}
strager
  • 88,763
  • 26
  • 134
  • 176
  • 37
    @FuzzyDunlop, Yes, but if `attr` is `""` that would return `false` as well. It should be `true`, because an empty attribute is a valid attribute. Also, there's no need for a double-not because `if` casts it down to bool anyway. – strager Feb 04 '11 at 01:15
  • 4
    I think we use `||` instead of `&&` – Pyjcoder Apr 08 '22 at 12:36
  • @Pyjcoder In this case the use of `&&` is correct. If the attribute is not undefined AND not false it should continue in the `if` statement. If either condition ends up false it should skip over the `if`. In the case where you invert the code (possibly for returning or error handling) you would need to use `||` since you would want to catch only if either condition is matched – Roe May 11 '23 at 13:53
702

How about just $(this).is("[name]")?

The [attr] syntax is the CSS selector for an element with an attribute attr, and .is() checks if the element it is called on matches the given CSS selector.

Domenic
  • 110,262
  • 41
  • 219
  • 271
162

If you will be checking the existence of attributes frequently, I would suggest creating a hasAttr function, to use as you hypothesized in your question:

$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

$(document).ready(function() {
    if($('.edit').hasAttr('id')) {
        alert('true');
    } else {
        alert('false');
    }
});

<div class="edit" id="div_1">Test field</div>
karim79
  • 339,989
  • 67
  • 413
  • 406
126

You're so close it's crazy.

if($(this).attr("name"))

There's no hasAttr but hitting an attribute by name will just return undefined if it doesn't exist.

This is why the below works. If you remove the name attribute from #heading the second alert will fire.

Update: As per the comments, the below will ONLY work if the attribute is present AND is set to something not if the attribute is there but empty

<script type="text/javascript">
$(document).ready(function()
{
    if ($("#heading").attr("name"))
      alert('Look, this is showing because it\'s not undefined');
    else
      alert('This would be called if it were undefined or is there but empty');
});
</script>
<h1 id="heading" name="bob">Welcome!</h1>
Tristan Warner-Smith
  • 9,631
  • 6
  • 46
  • 75
  • 27
    if the name attr is present but empty string, the attribute would exist but the test would fail. – lambacck Jun 12 '10 at 04:01
98

Late to the party, but... why not just this.hasAttribute("name")?

Refer This

jakubde
  • 31
  • 1
  • 2
  • 4
Domenic
  • 110,262
  • 41
  • 219
  • 271
23

The best way to do this would be with filter():

$("nav>ul>li>a").filter("[data-page-id]");

It would still be nice to have .hasAttr(), but as it doesn't exist there is this way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JamesM-SiteGen
  • 802
  • 2
  • 11
  • 26
7
Object.prototype.hasAttr = function(attr) {
    if(this.attr) {
        var _attr = this.attr(attr);
    } else {
        var _attr = this.getAttribute(attr);
    }
    return (typeof _attr !== "undefined" && _attr !== false && _attr !== null);      
};

I came a crossed this while writing my own function to do the same thing... I though I'd share in case someone else stumbles here. I added null because getAttribute() will return null if the attribute does not exist.

This method will allow you to check jQuery objects and regular javascript objects.

rlemon
  • 17,518
  • 14
  • 92
  • 123
5

You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:

$("#change_password").click(function() {
    var target = $(this).attr("rel");
    if($("#" + target).attr("disabled")) {
        $("#" + target).attr("disabled", false);
    } else {
        $("#" + target).attr("disabled", true);
    }
});

The "rel" attribute stores the id of the target input field.

user398341
  • 6,339
  • 17
  • 57
  • 75
5

I wrote a hasAttr() plugin for jquery that will do all of this very simply, exactly as the OP has requested. More information here

EDIT: My plugin was deleted in the great plugins.jquery.com database deletion disaster of 2010. You can look here for some info on adding it yourself, and why it hasn't been added.

bmarti44
  • 1,247
  • 2
  • 14
  • 22