Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any danger in using an html object as attribute "name" in javascript object?

in linking javascript objects with 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);
item.name = element.name;
...

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

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

are there any dangers lurking in this approach?

like image 772
cc young Avatar asked Feb 21 '26 22:02

cc young


1 Answers

Object keys are strings. So, when you try to use a DOM object as an object key, it will call toString() on the DOM object and use that as the key. toString() on DOM objects returns non-unique things like this:

[object HTMLParagraphElement]

So, it won't cause an error, but it probably won't do what you want. It would probably make more sense to use the object's ID as the key and generate a unique ID to put on the object if the object doesn't already have an id.

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

like image 192
jfriend00 Avatar answered Feb 24 '26 13:02

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!