1

Aloha,

I found an answer to my question here. Basically i'm looking to tell if a tag has an attribute. I don't care what the value is, just if there is one.

I'm currently using:

$.fn.hasAttr = function (attr) {
    var attribVal = this.attr(attr);
    alert(attr+" ["+attribVal+"]");
    return (attribVal !== undefined) && (attribVal !== false);
};

This function is not working in Opera or Webkit. It returns true even if the attribute does not exist. The alert that I added shows that the attribVal is equal to blank, not false, not undefined, not null, but blank. Firefox and IE this works fine in as attribVal is undefined.

The problem is I want it to return true for a blank attribute, if its on the tag and false for no attribute on the tag.

Edit: expected results...

<tag />                    should be hasAttr('placeholder') = false
<tag placeholder />        should be hasAttr('placeholder') = true
<tag placeholder="" />     should be hasAttr('placeholder') = true
<tag placeholder="Hi" />   should be hasAttr('placeholder') = true

Edit: Current code

This works in WebKit and FF, not in IE or Opera.

Update After all this, my original code works, unless I am looking at the placeholder attribute. Opera and webkit return true for all four options when I'm looking at the placeholder attribute. See here for an example. I've updated my expected results to use the placeholder attribute.

Community
  • 1
  • 1
Justin808
  • 20,859
  • 46
  • 160
  • 265

3 Answers3

1

This should work in all browsers:

 $.fn.hasAttr = function (attr) {
     for (var i = 0; i < this[0].attributes.length; i++) {
         if (this[0].attributes[i].nodeName == attr) {return true}
     }
    return false;
 };
user229044
  • 232,980
  • 40
  • 330
  • 338
Neil
  • 3,229
  • 1
  • 17
  • 15
  • This worked in all the browsers i could test - IE(7/8), FF (Win/Mac), Opera (Win/Mac), Chrome (Win/Mac), Safari (Win/Mac) http://jsfiddle.net/4UJJk/12/ – Justin808 Feb 16 '11 at 20:42
0

You shouldn't check explicitly against undefined, but just check for falsy values.

return !!attribVal;

That will return false for null, undefined, "", NaN, 0 and of course false.

Read more about !!.

Update

Your desired behavior should be possible invoking Sizzle:

$.fn.hasAttr = function (attr) {
    var attribVal = this.attr(attr);
    return (typeof attribVal === 'string');
};

Example: http://jsfiddle.net/4UJJk/11/

jAndy
  • 231,737
  • 57
  • 305
  • 359
0

A simple, jQuery-ish solution would be:

$.fn.hasAttr = function(attr) {
    return this.is('[' + attr + ']');
};

jsFiddle. NB I haven't got access to IE or Opera right now to test this...

lonesomeday
  • 233,373
  • 50
  • 316
  • 318