Steve
Steve

Reputation: 4898

jQuery .data() method not working as expected

I have an element that I store some data for with jQuery's .data() method:

$('#myElement').data('rot', '10');

If I pull the outerHTML for the element, save it on a server, close the browser, and then come back and pull the outerHTML back from the server into a browser, the data value is gone, though all the inline styles and attributes I assigned to the element are still there. From this I'm assuming that the .data() method works by having the current instantiation of JavaScript save the data in some local memory that also has a link to the element. So the method works fine as long as you don't shut off JavaScript, i.e., close your browser. If you close the browser the data is gone. The inline styles and attributes, on the other hand, become part of the outerHTML so go off to the server and come back in tact. Am I seeing this right?

Thanks

Upvotes: 0

Views: 91

Answers (2)

Markus Hofmann
Markus Hofmann

Reputation: 3447

Try to use pure JavaScript if all other fails:

If you want to retrieve or update data attributes using existing, native JavaScript, then you can do so using the getAttribute and setAttribute methods, e.g.:

var myEl = document.getElementById('myElement');

    myEl.setAttribute('rot', '10');

var attributeRed = myEl.getAttribute('rot');

This method will work in all modern browsers, but it is not how data- attributes are intended to be used.

 
The second (new and improved) way to achieve the same thing is by accessing an element’s dataset property:

var myEl = document.getElementById('myElement');

    myEl.dataset.rot = '10';

var attributeRed = myEl.dataset.rot;

This dataset property — part of the new HTML5 JavaScript APIs — will return a DOMStringMap object of all the selected element's data- attributes. When using this approach, rather than using the full attribute name, you can ditch the data- prefix and refer to the custom data directly using the name you have assigned to it. Data attribute names which contain hyphens will be stripped of their hyphens and converted to CamelCase.

(Credit goes to: http://html5doctor.com/html5-custom-data-attributes/)

However, it's still recommended to use the native getAttribute and setAttribute methods for cross browser compatibility.

Upvotes: 0

try this code

$('#myElement').attr('data-rot', 10);

Upvotes: 2

Related Questions