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:
- Firefox 6
- Chrome 19 (disabled by default, see instructions to enable)
- Opera 15 (disabled by default, start Opera with
--js-flags=--harmony
to enable it). - Internet Explorer 11 (confirmed to exist in leaked build)
In all other browsers, WeakMap support can be achieved by loading the WeakMap.js polyfill.