Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between jQuery's attr() and getAttribute()

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

like image 661
James Allardice Avatar asked Nov 16 '11 09:11

James Allardice


People also ask

What is the difference between prop () and attr ()?

prop() method provides a way to explicitly retrieve property values, while . attr() retrieves attributes. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the . prop() method.

What is ATTR attribute?

The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.


1 Answers

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

like image 193
Matt Avatar answered Oct 02 '22 14:10

Matt