I would like to store an object in Javascript in a custom attribute of a DOM node. I've tried setAttribute/getAttribute, but they convert the attribute into text.
Assume I've already done
node = document.getElementById( 'SAMPLE' );
object = { test: function( ){ stuff; } };
This doesn't work anywhere I've tested
node.setAttribute( 'info', object );
val = node.getAttribute( 'info' ) ;
because it leaves val with a string value.
If I do
node[ 'info' ] = object;
then
val = node[ 'info' ];
gives me back my object later in my script.
Will this work in pre-HTML5 browsers like old IEs? Is it safe?
You can "attach" it as a property, but that's not a good idea. – RobG
So, here's my suggestion for an alternative:
Generate a unique string - easy way might be Date.now().toString()
unless you're generating them in a loop or something. Use whatever works best here.
Have a global object, say domdata = {};
Assign domdata[unique_string] = your_data_here;
Save node.setAttribute("data-dom-id",unique_string);
You can now retrieve the data with:
Get unique_string = node.getAttribute("data-dom-id");
Retrieve domdata[unique_string]
Done! :)