Is it ok to set custom properties on DOM elements, and rely on them persisting?
For example, given
<html><body><div id="foo"></div></body></html>
Would it be fair to do document.getElementById('foo').bar = "baz";
, and expect document.getElementsByTagName('div')[0].bar
to equal "baz"
?
Note that I'm talking about properties as in normal javascript object properties here, not element attributes.
I'm interested both in how cross-browser it is, and whether its supported in any spec.
Does the DOM API guarantee that the same javascript object will be returned for the same DOM element every time?
As a general rule, don't use custom properties. You shouldn't modify DOM objects in ways they don't expect because they may not behave the way you think they will.
The mechanism for custom attributes in HTML5 is to use the data- prefix. If you use set/getAttribute for data- attributes, you should be OK as no standard attribute should be introduced in the future with a data- prefix (but other code in the page still might do so).
But having said that, I would still recommend using a custom object to store the values and referencing them by element id or class or some other standard (as in HTML 4.01) attribute value. It avoids the issue of custom properties and attributes and is known to work everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With