Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  167] [ 6]  / answers: 1 / hits: 20961  / 13 Years ago, wed, november 16, 2011, 12:00:00

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).


More From » jquery

 Answers
20

Because 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).


[#89092] Tuesday, November 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daquanmilesw

Total Points: 57
Total Questions: 102
Total Answers: 110

Location: Wallis and Futuna
Member since Sat, Aug 6, 2022
2 Years ago
daquanmilesw questions
;