I have a question about .data(). In a stackoverflow answer, jquery saves data in cache object where cache index is suffixed with a hash of the dom element. For example, consider
The way in which jQuery data works is by storing all the data internal in a variable called cache
. Each jQuery session creates a "expando" which is basically a random string like jquery161362319162
specific to that session. This is placed on each object in the DOM such as element.jquery161362319162 with a value of the index in cache.
Here is a very basic example of roughly how it works. This will need a bit more work to add support for multiple data on an element, but you'll get the idea of how it works internally.
var cache = []; // Stores all the data for each element
var uid = 'jquery89437507043'; // random generated id,
// jQuery uses a function to automatically
// generate such a value
function data(element, key, data)
{
if (data !== undefined) // We are setting data
{
var thisCache[key] = data;
cache.push(thisCache)
element[uid] = cache.length; // Place the index cache
// for this data set on the element
}
else
{
return cache[element[uid]][key];
}
}
var div = $('div').get(0);
data(div, 'test', { 'apple': 'juice' });
alert(data(div, 'test').apple); // Will alert 'juice'
I'm not sure you have understood what you have done with the JQUERY selectors.
In your example HTML you nested 2 divs and then placed a single paragraph into the lowest level div. Then in your JQUERY you asked it to look for 2 divs and a paragraph. That's why you got the "correct" result. This actually has nothing to do with .data()
as such, but the fact that there wasn't anything else for JQUERY to find, and therefore the result was always going to be "correct".
However, I'm not certain you would get the "correct" result if you had a larger context with many nested divs that had no id values.
I would say that it is good practice for you to assign an id value for all your <div>
and then pass the specific id whenever you use .data()
.
In that way you can know what the outcome of your code will be as you create it.