Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use HTML elements as Object keys?

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?

like image 546
ketan Avatar asked Apr 15 '26 06:04

ketan


1 Answers

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));
like image 126
pretzelhammer Avatar answered Apr 17 '26 19:04

pretzelhammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!