Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
sesquized Avatar asked Nov 02 '25 05:11

sesquized


1 Answers

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! :)

like image 51
Niet the Dark Absol Avatar answered Nov 03 '25 21:11

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!