Skip to content Skip to sidebar Skip to footer

Storing An Html Node As Key In An *object*

Similar to this SO question, I would like to use HTML nodes as keys in an object (not an array). Example: var _hotspots = { [object HTMLDivElement] : { someProps:[

Solution 1:

The keys of JavaScript objects are always character. You could store the id as the key and then retreive the element in your function.

Solution 2:

It's now possible to do this with Map or Set objects, but a Map is more appropriate if you want to store key value pair, such as a regular object.

You could still add node as key with regular objects, but the problem is that the node is converted to a string, because objects can only store keys as strings, this means that the object can't distinguish unique nodes that have identical attributes/structure.

The reason Map works is because its keys can be any value, including functions, objects, or any primitive.

const divEl1 = document.querySelectorAll("div")[0];
const divEl2 = document.querySelectorAll("div")[1];

const obj = {};
const map = newMap();

obj[divEl1] = divEl1.getBoundingClientRect();
map.set(divEl1, divEl1.getBoundingClientRect());

console.log("Object: is divEl1? ", !!obj[divEl2]);
console.log("Map: is divEl1? ", map.has(divEl2));
console.log("Map: get divEl1 bounding properties", map.get(divEl1));
<body><divclass="foo"data-some-id="1">I am a <span>div</span></div><divclass="foo"data-some-id="1">I am a <span>div</span></div></body>

Solution 3:

You could use my own jshashtable, which accepts any object as key, but if it's not a problem for you to give all your elements an id then I'd recommend using an object with element IDs as keys, since that will be the simplest and most performant solution.

Post a Comment for "Storing An Html Node As Key In An *object*"