tags:

views:

491

answers:

3

I want to associate a javascript object with an HTML element. Is there a simple way to do this.

I noticed in the HTML DOM (http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html) defines a setAttribute method and it looks like this is defined for arbitrary attribute name. However this can only set string values. (You can of course use this to store keys into a dictionary.)

Specifics (though I'm mostly interested in the general question)

Specifically, I have html elements representing nodes in a tree and I'm trying to enable drag-and-drop, but the jquery drop event will only give me the elements being dragged and dropped

The normal pattern for getting information to event handlers seems to be to create the HTML elements at the same time as you are creating javascript objects and then to define event handlers by closing over these javascript objects - however this doesn't work too well in this case (I could have a global object that gets populated when a drag begins... but this feels slightly nasty)

+6  A: 

Have you looked at the jQuery data() method? You can assign complex objects to the element if you want or you can leverage that method to hold a reference to an object (or some other data) at the very least.

Phil.Wheeler
Thank you: This is pretty much what I was looking for.Interestingly to define this method jquery stores keys into a global dictionary in a string attribute on each element. The name of this string attribute is randomly generated when jquery is first loaded. (Suggesting that there isn't a good way to do there isn't a nicer way to do this only using the DOM)
+3  A: 

JavaScript objects can have arbitrary properties assigned to them, there's nothing special you have to do to allow it. This includes DOM elements; although this behaviour is not part of the DOM standard, it has been the case going back to the very first versions of JavaScript and is totally reliable.

var div= document.getElementById('nav');
div.potato= ['lemons', 3];
bobince
@tat.wright - The arbitrary properties on HTML elements he's speaking of are called Expando properties. Also note that div.potato does not mean div.getAttribute("potato")
nickyt
It's not totally reliable at all. For example, one call to `document.expando = false` in IE prevents all expando properties on HTML elements within the document.
Tim Down
@Tim Down: then just don't do it. I fail to see why it isn't reliable - it's like saying that the String object is unreliable, because you can set it to null.
simon
@simon - not really. There are good reasons for setting `document.expando = false` (e.g. preventing accidental misspellings of DOM properties being silently accepted). Also, IE doesn't allow expando properties on all objects (for example, ActiveX objects such as XMLHttpRequest in IE6, at least).
Tim Down
A: 

If you don't want the unnecessary bloat of introducing jQuery, you could use jshashtable with DOM elements as keys.

Tim Down