Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  105] [ 2]  / answers: 1 / hits: 55820  / 15 Years ago, wed, september 9, 2009, 12:00:00

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



I noticed HTML DOM 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).


More From » dom

 Answers
43

If you're already using jQuery, you can use its data() method for this. This allows you to 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.


It's worth noting that, under the hood, jQuery implements data() in precisely the way that bobince described in his answer, so you always use that directly, whether or not you're using jQuery.


[#98723] Saturday, September 5, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
;