Search code examples
javascriptdomsetattributegetattribute

Can I store a non-text property in a DOM node in Javascript


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?


Solution

  • You can "attach" it as a property, but that's not a good idea. – RobG

    So, here's my suggestion for an alternative:

    1. 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.

    2. Have a global object, say domdata = {};

    3. Assign domdata[unique_string] = your_data_here;

    4. Save node.setAttribute("data-dom-id",unique_string);

    You can now retrieve the data with:

    1. Get unique_string = node.getAttribute("data-dom-id");

    2. Retrieve domdata[unique_string]

    Done! :)