10

I want to create a hash with DOM elements as keys. This is illustrated by the following code:

var hash = {};
var set = function(element, value) {  hash[element] = value; };
var get = function(element)        {  return hash[element];  };

set(document.getElementById('foo'), 'bar');
get(document.getElementById('foo')); // returns 'bar'

How can I ensure that hash maps to a unique value for each Element?
Note that I can't use the raw ID string as key, because any arbitrary Element may be passed in, including those without a id.

6
  • 1
    why would you document.getElementById when you can directly use the id? Commented Jun 23, 2013 at 20:54
  • 1
    @KarolyHorvath Sorry this was a simplified example, I do need to key off the element. Commented Jun 23, 2013 at 20:55
  • You may want to check this thread on unique arrays Commented Jun 23, 2013 at 20:56
  • @KarolyHorvath what do you mean? Commented Jun 23, 2013 at 22:28
  • 1
    @GriffLab Many DOM nodes do not have an "id" attribute, so these cannot be uniquely identified by their id string. The OP wants to get the ability to use any DOM node as key. Commented Jun 23, 2013 at 22:33

1 Answer 1

10

In JavaScript until ES 6, only strings can be used as a key. If you want to use DOM elements, either use two linked lists, or the WeakMap object. A bonus of the latter method is that it does not cause memory leaks.

Applied to your example:

var hash = new WeakMap();
hash.set(document.getElementById('foo'), 'bar');
hash.get(document.getElementById('foo')); // returns 'bar'

As of writing, WeakMap is only supported by the following browsers:

In all other browsers, WeakMap support can be achieved by loading the WeakMap.js polyfill.

Sign up to request clarification or add additional context in comments.

4 Comments

"Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes."
@gdoron A polyfill is available, such as Weakmap.js, in case you worry about browser compatibility.
"A bonus of the latter method is that it does not cause memory leaks." I'd argue in this case OP should just use a regular map.
This answer is not correct in current chrome; HTMLDivElement instances will act as the same key as their .toString() representation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.