Alternative to hiding data in divs?

Too often, I find myself storing object data in hidden dom elements. I was curious if there is a way to bind this data to the dom node. When I try to create attributes on the fly, it doesn't seem to work. It would be much easier to access the this.something property instead of accessing the html contained in the child. I feel that I need to know how to do this, but I do not. Thanks.

+7
source share
2 answers

Absolutely! jQuery .data() .

 $('#someId').data('myData', someValue); // To store the data $('#someId').data('myData'); // To retrieve it again 

Any JavaScript variable can be stored as data - it is not limited to strings.

Note that this does not actually attach the data to the DOM node, as you say (which should be avoided). jQuery stores its own cache of all the data and DOM nodes you store to which you want to connect them. So this is not the same as domNode.myData = someValue .

+9
source

jQuery.data is the preferred way to do this.

+1
source

All Articles