Any danger when using html object as "name" attribute in javascript object?

when linking javascript objects to html objects

// javascript element
var element = { tag:'input', name: 'email', value:null, dom: null,
   verifyFunc: function() {...}, postFunc: function() {...},
   rcdElement: some_element }

// lookup javascript element from dom
var doms = {};

// create html element for dom
var item = document.createElement(element.tag); =;

// cross-link
doms[item] = element;
element.dom = item;

// using it in generic "onchange" trigger
function changeTrigger(e) {
  var el = doms[];


Are there any dangers lurking in this approach?


source to share

2 answers

Object keys are strings. So when you try to use a DOM object as a key object, it calls toString()

on the DOM object and uses it as a key. toString()

on DOM objects, non-unique things like this are returned:

[object HTMLParagraphElement]


This way it won't throw an error, but it probably won't do what you want. It would probably be wiser to use the object ID as the key and create a unique ID to place the object if the object doesn't already have an ID.

As far as I can tell, any use of using an object as a key can also be done with an id as a key.



When I run this in Firefox 10:

window.onload = function(){
    var doms = {},
        element = { 
            tag: 'input', 
            name: 'email', 
            value: null,
            dom: null

    for (var i = 0; i < 10; i++) {
        item = document.createElement(element.tag); = + i;

        doms[item] = element;



In the Firebug console, I see the following:

Object { [object HTMLInputElement]={...}}


Expands to:

[object HTMLInputElement]   Object { tag="input", name="email", value=null, more...}

dom                         null

name                        "email"

tag                         "input"

value                       null

Please note that there is only one reference / object pair, not ten. I suspect that you cannot do this, and I would advise against it anyway (instead of a specific quote supporting my guess).



All Articles