tags:

views:

5646

answers:

5

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")) {
    function etc()
}
+2  A: 

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.

<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');
});
</script>
<h1 id="heading" name="bob">Welcome!</h1>
TreeUK
OK, I will explain. if ($("#heading").attr("name")) returns undefined if false. So, if you print $("#heading").attr("name"), you will get 'undefined' if there is nothing. Whereas if($(this).attr('name') !== undefined) returns false, printing it would give nothing. There's a huge inherent difference between 'false' and 'undefined'.
Mark
The behaviour is the same in both cases though. You can swap an evaluation of false with undefined in the instance I'm showing there. .attr("name") isn't returning false, but it's evaluating to false. So you can use it in exactly the way above.
TreeUK
if the name attr is present but empty string, the attribute would exist but the test would fail.
lambacck
+12  A: 
if($(this).attr('name') !== undefined) {
    // ...
}
strager
Ahah, thanks. This is the right answer for me because returning undefined is not what I want.Thanks again.
Mark
+12  A: 

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
Great tip, thanks!
Mark
@TreeUK - not a typo, !== is what I meant.
karim79
Cool, I hadn't seen that before :) [!== is not exactly equal to (value and type)]
TreeUK
A: 

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.

JamesM
A: 

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.