I understand I can build an array of references to elements/nodes. I realize also that I could use the neat trick of treating an array like a heap (index 2n and 2n+1 for children) to build a (potentially wasteful) binary search tree using it.
But all that’s still not enough for the premature optimizer in me. Besides, implementing a BST is going to be bug prone.
Here’s my question. Can I somehow use an element reference as index into javascript’s hashes (which are objects, or vice versa?). If not, can I conjure up a unique string from an element reference, which I can then use as my hash key? If not, how the hell does jQuery do it?
The easiest option is to just use your own attribute on the DOM object:
Here’s the general idea behind how jQuery’s
.data()function works that you could use in your own plain javascript. It uses one custom attribute on the object and then stores everything else in a data structure indexed by the value of that custom attribute.It is a bit more involved to store multiple attributes for a given object in the data object, but this is the general idea.
And, if you can use jQuery, it’s trivial:
If you want to really see how jQuery’s
.data()works, you can step through the first call to set data and then retrieve it when using the unminified jQuery. It’s easy to see what it does.