Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  7] [ 3]  / answers: 1 / hits: 5956  / 10 Years ago, wed, august 13, 2014, 12:00:00

And before someone says:



document.querySelector('.myElem').getAttribute('data-*')


No, is not what I'm looking for. jQuery's data() has dual functions. 1) It queries an HTML5 data attribute which can be seen in the HTML code like this:



<div data-role=page data-last-value=43 data-hidden=true data-options='{name:John}'></div>
$( div ).data( role ) === page;
$( div ).data( lastValue ) === 43;
$( div ).data( hidden ) === true;
$( div ).data( options ).name === John;


and 2) the ones that are set by .data(name, value) which are hidden in a jQuery internal Object, to which the documentation only says to save information under the names 'events' and 'handle', yet I haven't figured out a way to access them or what actually creates them.



So, my question stands, how can I access the jQuery data values from plain JavaScript?



Just so it's absolutely clear... let me put more emphasis: I don't want the data- HTML attributes, but the jQuery object data.


More From » jquery

 Answers
9

jQuery uses internal object called $.cache to store event handlers and data values. $.cache is a simple dictionary which can look something like this:



{ 1: { data: { role: page}, events: { click: ...} }, 2: { ... }}


The keys are all unique indexes corresponding to some DOM nodes. If your DOM element was previously touched by jQuery (attached events or to some data), you will see that it has a weird property similar to the one below:



jQuery17108624803440179676: 2


Here jQuery17108624803440179676 is a unique string generated by jQuery when it was loaded on the page. This unique identifier is called expando and is stored as



$.expando


Now that you know how to access an individual element's internal data by bypassing jQuery's data API...



$.cache[element[$.expando]]


...you may ask why jQuery uses an intermediate object to store all DOM data and events. The reason is that it is a way to avoid memory leaks, which would be the case if data and events handlers were stored directly in DOM elements properties (due to circular references).



Having said all that, I want to emphasize that you should not work with node data objects other than that via the jQuery Data API for the simple reason that it handles all the complex stuff behind the scenes.


[#43151] Tuesday, August 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yosefleod

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;