8

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.

Rob W
  • 315,396
  • 71
  • 752
  • 644
Kevin Sylvestre
  • 34,782
  • 30
  • 138
  • 226

1 Answers1

9

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.

Community
  • 1
  • 1
Rob W
  • 315,396
  • 71
  • 752
  • 644
  • 3
    _"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 is supporting Monica Jun 23 '13 at 21:01
  • 1
    @gdoron A polyfill is available, such as [Weakmap.js](https://code.google.com/p/es-lab/source/browse/trunk/src/ses/WeakMap.js), in case you worry about browser compatibility. – Rob W Jun 23 '13 at 21:04
  • "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. – Benjamin Gruenbaum Jan 16 '16 at 19:29