user572559
user572559

Reputation:

JavaScript use custom attributes as persistance mechanism

I need to keep the state of my Html control (I've a multi select list and I need to keep the info about selected items), for which I'm using a custom attribute like:

// put
$("#element").attr("selectionState", "value");

// get
alert($("#element").attr("selectionState"));

While it works, I wonder if it's a safe approach and if not, how would you solve the problem?

The only risk I can see is - another script creating custom attributes with the same names, which is something I can manage.

Upvotes: 0

Views: 72

Answers (1)

Pointy
Pointy

Reputation: 413737

I suggest using .data() instead.

$('#element').data('selectionState', 'value');

It's definitely safer, as it keeps the data completely in JavaScript instead of the "attributes" maps in the DOM elements. Sins ".data()" is all JavaScript, you can store anything there, including functions and closures. (I guess you could do that with ".attr()" too but it's pretty risky in IE, which, in old versions at least, had quite different storage management internally for DOM and for JScript.)

The namespace problem you allude to is of course the same, as would be the possible ways of managing it.

Upvotes: 3

Related Questions