Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

an alternative to hiding data in divs?

All too often I find myself storing object data in hidden dom elements. I was curious if there was a way to attach this data to the dom node itself. When I try to create attributes 'on the fly', it doesn't seem to work. It would be much easier to access the property with this.something instead of accessing the html contained in a child. I feel like I should know how to do this, but I don't. Thanks.

like image 295
Brandon Frohbieter Avatar asked Feb 04 '11 00:02

Brandon Frohbieter


1 Answers

There absolutely is! jQuery's .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's not limited to strings.

Note that this doesn't actually attach data to the DOM node as you say (which should be avoided). jQuery keeps its own cache of all the data you store and the DOM nodes you wanted to attach it to. So, it's not the same as domNode.myData = someValue.

like image 143
David Tang Avatar answered Sep 28 '22 18:09

David Tang