1
<div id="theDiv"></div>

document.getElementByid('theDiv').myProperty='myValue';

if('undefined'!==typeof document.getElementById('theDiv').myProperty){

Is it ok and cross browser compatible to give DOM objects custom properties to be used later on?

If the properties only need to be set and retrieved via javascript can this be used instead of setAttribute / getAttribute?

anonymous-one
  • 14,454
  • 18
  • 60
  • 84
  • Yes, this is perfectly legal and acceptable. Just be careful not to overwrite [something default](https://developer.mozilla.org/en/docs/Web/API/HTMLElement). However keep in mind you'll possibly have to keep changing it in future versions, which will make maintaining your code rather difficult. – blgt Jul 19 '14 at 19:15
  • I have created a jQuery plugin to implement the same. Are you using jQuery? – Ruchir Gupta Jul 21 '14 at 16:18

1 Answers1

1

Edit 2014/07/21

According to @blgt comment and everything else I read, it seems that the future proof issue is the only problem you could encounter.

Actually, doing a jsperf on it shows it's even a bit faster than setAttribute / getAttribute


Should be comment

Maybe this answer may help you : https://stackoverflow.com/a/3363501/3702797

or this question

and particularly this answer

Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I know about setAttrbiute / getAttribute, but are there any issues with the notation I used above? – anonymous-one Jul 19 '14 at 19:08
  • Updated answer but I'm no specialist sorry… – Kaiido Jul 19 '14 at 19:13
  • The "this answer" is particularly helpful. But I am curious if aside from the possibility of future-collisions, there are any downsides. – anonymous-one Jul 19 '14 at 19:52
  • According to @blgt comment and everything else I read, it seems to be the only one, in fact, doing a jsperf on it shows [it's even a bit faster](http://jsperf.com/qssdqsdqd/3) than setAttribute / getAttribute – Kaiido Jul 20 '14 at 14:12