I’d like to create a correlation between data and DOM nodes. I tried to directly create a Object, with the nodes as properties, but it looks like only the string representations of the nodes are used.
To make the problem more concrete, let’s say I have the below document, and I want to associate the first div with the number 3, and the second div with the list ['x', 'y', 'z'], how would you do this?
<html> <body>
<div/>
<div/>
( 100 more divs )
</body> </html>
I see that jQuery has a .data() method just for doing this. Is that the only way? This seems like such a fundamental operation that I had expected to do it with plain-old javascript.
The intent is to register an onclick event with these nodes, and have the data on hand.
window.onload = function() {
var index2data = { 0:3, 1:['x', 'y', 'z'] };
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
setData( divs[i], index2data[i] )
divs[i].onclick = onClick;
}
}
function onClick() {
var data = getData( this );
// do a bunch more stuff
}
In order of keeping the actual data separate from the DOM you can try to set div IDs for all elements by script – in doing so you should test if any div already has an id and use that instead in order of not breaking things…
And now applied to your example case: