javascript – Add properties to [Node] element


Is it okay to add custom properties directly to the [Node] element? For example:

document.getElementById('minhaDiv').minhaPropriedade = 'teste';

I'm using Firefox and I haven't had problems setting or getting ownership, but is this something I should avoid? Why?


It is generally recommended to avoid. Main reason: You might end up causing a name collision with a property that will be implemented in the DOM in the future. So, even though the code doesn't cause any problems today, in the future it might.

Another aspect is that this is halfway there so that later you will feel like extending the DOM, that is, extending the prototypes of native DOM objects like HTMLElement . This is not a good idea as these objects are much more susceptible to quirks that vary by implementation – and it is the language specification itself that gives implementers of so-called host objects this freedom .

For more details on all this, the great reference is the following Kangax article: What's wrong with extending the DOM? Although the article is from 2010, when the browser landscape was different, the language specification hasn't changed (yet), so much of what's said there remains valid – except perhaps for the performance and bug-specific analyzes of certain browsers.

Scroll to Top