The jQuery documention for the attr
method states that:
Attribute values are strings with the exception of a few attributes such as value and tabindex.
And that does seem to be the case. Consider the following element:
<input type="text" id="example" tabindex="3">
The following line does indeed show "number", not "string":
alert(typeof $("#example").attr("tabindex")); //Number
Now, the thing that's confusing me is that when using the DOM method getAttribute
, you get a different result:
alert(typeof $("#example")[0].getAttribute("tabindex")); //String
Looking at the jQuery source for the attr
method, it appears that jQuery simply returns what getAttribute
returns, so why is there a difference? Here's the relevant lines of the jQuery source:
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
And here's a fiddle to demonstrate the issue. Just to confuse matters further, I've tried it in Chrome 15, Firefox 8, IE8 and IE7, and all behave as described above, except for IE7, which alerts "number" for both (which is what I would expect to happen).
The jQuery documention for the attr
method states that:
Attribute values are strings with the exception of a few attributes such as value and tabindex.
And that does seem to be the case. Consider the following element:
<input type="text" id="example" tabindex="3">
The following line does indeed show "number", not "string":
alert(typeof $("#example").attr("tabindex")); //Number
Now, the thing that's confusing me is that when using the DOM method getAttribute
, you get a different result:
alert(typeof $("#example")[0].getAttribute("tabindex")); //String
Looking at the jQuery source for the attr
method, it appears that jQuery simply returns what getAttribute
returns, so why is there a difference? Here's the relevant lines of the jQuery source:
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
And here's a fiddle to demonstrate the issue. Just to confuse matters further, I've tried it in Chrome 15, Firefox 8, IE8 and IE7, and all behave as described above, except for IE7, which alerts "number" for both (which is what I would expect to happen).
Share Improve this question asked Nov 16, 2011 at 9:17 James AllardiceJames Allardice 166k22 gold badges334 silver badges315 bronze badges1 Answer
Reset to default 12Because jQuery defines a propHook for tabIndex
which explicity parseInt
's the return type;
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
This hook is then added to the attrHook
which is why the behaviour is observed in the attr
function (and why it first appears no attrHook is defined for tabIndex
).