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.
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:
--js-flags=--harmony
to enable it).In all other browsers, WeakMap support can be achieved by loading the WeakMap.js polyfill.