Unraveling data( ) vs attr( ) JQuery methods

In theory, you can use $(elem).data() and $(elem).attr() methods interchangeably, but in practice, this may lead to confusion and hard to debug defects. Although both methods are designed to save and retrieve values, they accomplish this task in different ways. The data() method stores the provided data in a DOM element , whereas attr() sets a (string) value to the corresponding html element.

To see the difference in practice please refer to the example below:

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"/>
    <span id="sp1" data-attr1="attr-1">span1</span><br>
    <span id="sp2">span2</span>
    <script type="text/javascript">
      $("#sp2").attr("data-attr2", "attr-2");
      $("#sp1").data("attr3", "data-3");
      $("#sp1").attr("data-attr3", "attr-3");
      $("#sp1").data("data-attr4", "data-4");

Corresponding javascript code:

// will return attr-1
// will return undefined
// will return attr-1
// will return attr-2
// will return data-4
// will return undefined
// will return data-3
// will return attr-3

Additional notes:

– Values set by attr() method will be visible on the html element (you can verify this by inspecting the element using Firebug or the Chrome developer console), whereas the data() method adds it only to the DOM object.

– The data() method stores and returns an object, but the attr() method always operates on a string, so be careful if you are expecting a a float or an integer result. (In this instance, use the javascript parseFloat() method to convert the string result to a float.)

– Also, for performance reasons, use the data() method on the element directly instead of using the generic data() method where the target element is one of the parameters.

for example, use this:

theInput.data('someData', 'newValue');

instead of this:

$.data(theInput, 'someData', 'newValue');

In summary, use only one of the two methods, if possible, to avoid confusion and make the code more maintainable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: