What’s wrong with adding properties to DOM Element objects?

Is there a problem adding properties (or methods) directly to DOM Element Objects?


There is no web standard that says you can add arbitrary properties to DOM nodes. They are ‘host objects’ with browser-specific implementations, not ‘native JavaScript objects’ which according to ECMA-262 you can do what you like with. Other host objects will not allow you to add arbitrary properties.

In reality since the earliest browsers did allow you to do it, it’s a de facto standard that you can anyway… unless you deliberately tell IE to disallow it by setting document.expando= false. You probably wouldn’t do that yourself, but if you’re writing a script to be deployed elsewhere it might concern you.

There is a practical problem with arbitrary-properties in that you don’t really know that the arbitrary name you have chosen doesn’t have an existing meaning in some browser you haven’t tested yet, or in a future version of a browser or standard that doesn’t exist yet. Add a property element.sausage= true, and you can’t be sure that no browser anywhere in space and time will use that as a signal to engage the exciting DOM Sausage Make The Browser Crash feature. So if you do add an arbitrary property, make sure to give it an unlikely name, for example element._mylibraryname_sausage= true. This also helps prevent namespace conflicts with other script components that might add arbitrary properties.

There is a further problem in IE in that properties you add are incorrectly treated as attributes. If you serialise the element with innerHTML you’ll get an unexpected attribute in the output, eg. <p _mylibraryname_sausage="true">. Should you then assign that HTML string to another element, you’ll get a property in the new element, potentially confusing your script.

(Note this only happens for properties whose values are simple types; Objects, Arrays and Functions do not show up in serialised HTML. I wish jQuery knew about this, because the way it works around it to implement the data method is absolutely terrible, results in bugs, and slows down many simple DOM operations.)

Leave a Comment