Search code examples
javascriptdom

Can I add arbitrary properties to DOM objects?


Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT> or <SELECT> elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?


Solution

  • Sure, people have been doing it for ages. It's not recommended as it's messy and you may mess with existing properties.

    If you are looping code with for..in your code may break because you will now be enumerating through these newly attached properties.

    I suggest using something like jQuery's .data which keeps metadata attached to objects. If you don't want to use a library, re-implement jQuery.data