Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript DOM: Setting custom DOM element properties

Tags:

javascript

dom

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?

like image 989
rampion Avatar asked Sep 05 '25 02:09

rampion


1 Answers

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.

like image 78
RobG Avatar answered Sep 06 '25 21:09

RobG