buy prednisone

data() vs attr() – pick the right method!

Background
jQuery introduced jQuery.data() back in 2008 as a way to store data inside an associate JavaScript object.

A couple of years later, HTML5 became popular and it introduced a way to write custom attributes using the data- prefix. These custom data attributes can be accessed via the native .dataset object. However, this is a little different than jQuery’s original idea of an internal data object. Custom attributes involve values being associated with HTML elements in the markup and not DOM elements in memory. On the other hand, jQuery.data() would not update attributes in the markup that happen to have the same name.

HTML5 custom attributes and jQuery’s internal data object are therefore two different concepts!

See this excellent article: http://www.learningjquery.com/2011/09/using-jquerys-data-apis

In practice

jQuery.data() and .attr() can easily be misused and lead to unexpected bugs.

Examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> $0
<h2 data-description="Delicious">​NOODLE & RICE​</h2>
> $($0).data('description', 'Bad food actually')
[<h2 data-description="Delicious">​NOODLE & RICE​</h2>]

> $($0).data('description')
"Bad food actually"
> $0.dataset.description
"Delicious"
> $($0).attr('data-description')
"Delicious"

> $($0).removeData('description')
[<h2 data-description="Delicious">​NOODLE & RICE​</h2>]

This shows that the jQuery data object and the custom attribute are disconnected. Updating the jQuery data object wouldn’t update the custom attribute.

Rules
It is important to understand the differences between data attributes and jQuery’s internal data object.

Picking the right place to store information:

Use jQuery’s internal data object when –
1) storing complex JSON/ JavaScript objects
2) storing sensitive and temporary data (might consider data encryption)

Use HTML5 data-* custom attributes when –
1) information is easily available in the HTML template
2) information being stored is directly used to create UI feedback upon control events (e.g. mouseover, click)
3) elements related need to be queried using CSS or Sizzle selectors

Picking the right method:

1) To update or remove HTML5 data-* custom attributes, use jQuery’s .attr() or .removeAttr() methods. See bug tracker ticket: http://bugs.jquery.com/ticket/10668
2) When accessing data taken from data-* attributes, and especially when accessing the data object directly, use the W3C camelCasing conventions.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>