I'm trying to create an Object with HTML elements as keys. I create the keys using document.createElement('div'), but when I try to insert both into an Object the second key ends up replacing the first:
let a = document.createElement('div');
let b = document.createElement('div');
let obj = {};
obj[a] = 3;
obj[b] = 'x';
console.log(obj);
Is there a way to do this without any keys or values getting replaced?
Objects can only hold string keys. Your divs are being serialized to strings and then overriding each other. If you would like to hold HTML Elements as keys you should use a Map like so:
let a = document.createElement('div');
let b = document.createElement('div');
let map = new Map();
map.set(a, 3);
map.set(b, 'x');
// use Array.from to pretty print the result
console.log(Array.from(map));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With