1

Relevant discussion.

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?

Community
  • 1
  • 1
Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • What are you trying to achieve? A fast lookup from a DOM node to your own data structure? If so, you can always attach custom properties to node objects. – Ates Goral Sep 28 '11 at 03:41
  • @AtesGoral, You are correct that is what i am trying to achieve. I was not aware of the difference between attributes and properties. Will editing properties on a given node persist over the life of that node (as it exists in the document)? – Steven Lu Sep 28 '11 at 05:57
  • I'm not a 100% sure, but the properties for a particular DOM node _should_ persist during the life time of that node. I don't know if there are special cases on certain browsers that cause a new JS object to be assigned to an existing DOM node... – Ates Goral Sep 28 '11 at 14:25

1 Answers1

1

The easiest option is to just use your own attribute on the DOM object:

var element = document.getElementById("test");
element.myData = "whatever";

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.

var idCntr = 0;   // global cntr

var data = {};
var element = document.getElementById("test");
var id = element.uniqueID;
if (!id) {
    id = idCntr++ + "";
    element.uniqueID = id;
}
data[id] = "whatever";


// then some time later, you can do this
var element = document.getElementById("test");
console.log(data[element.uniqueID]);   // whatever

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:

$("#test").data("myData", "whatever");  // sets the data

console.log($("#test").data("myData"));   // retrieves the data

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979