Add properties to the [Node] element

Asked

Viewed 90 times

5

Is there a problem with adding custom properties directly to the [Node] element? For example:

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

I’m using Firefox and I haven’t had problems with setting or getting the property, but is it something I should avoid? Why?

  • 2

    Here you can see a very interesting article on the subject.

  • Oeslei, I wrote my answer a little fast. I think it would be better to leave to accept an answer later, to encourage other, potentially more complete, responses to be posted. More about that at the finish line: We must be in a hurry to accept answers?

1 answer

6


It is something that is usually recommended to avoid. Main reason: you may end up causing a name collision with a property that will be implemented in the DOM in the future. So even if today the code does not cause any problems, in the future it may cause.

Another aspect is that this is half way to later have the will to extend the DOM, that is, to extend the prototypes of native objects of the DOM as HTMLElement. This is not a good idea because these objects are much more susceptible to peculiarities that vary according to the implementation - and it is the language specification itself that gives that freedom the implementers of the so-called host Objects.

For more details on all this, the big reference is the following article from Kangax: What’s Wrong with Extending the DOM? While the article is from 2010, when the browser landscape was different, the language specification has not changed (yet), so much of what is said there remains valid - except perhaps for the performance and bug analyses specific to certain browsers.

  • Note: now yes the specification has changed. Maybe it’s time for all this discussion to be reevaluated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.