I feel like this should have a really simple answer, but I’m still scratching my head and Google isn’t helping. I’m trying to store information about an element in an array. However in Google Chrome, when I set information about the second element, it overwrites the first. Here’s the simplified version of the code:
<!DOCTYPE HTML>
<html>
<head>
<script>
var $box = new Array();
$box['test'] = new Array();
function load(){
$box['test'][document.getElementById('box')] = true;
$box['test'][document.getElementById('boxinfo')] = false;
console.log('box: ' + $box['test'][document.getElementById('box')]); // box: false // Should be true
console.log('boxinfo: ' + $box['test'][document.getElementById('boxinfo')]); // boxinfo: false // Should be false
console.log(document.getElementById('box') == document.getElementById('boxinfo')); // false // Should be false
}
</script>
</head>
<body onload="load();">
<div id="box">
<div id="boxinfo">BoxInfo</div>
Box
</div>
</body>
</html>
How can I make it so that
$box['test'][document.getElementById('box')] // is true
$box['test'][document.getElementsByTagName('div')[0]] // is true
$box['test'][document.getElementById('boxinfo')] // is false
When doing
baris converted into a String value, which is then used as the property name (which is being assigned to). In your case, your DOM elements are converted into strings like'[object HTMLDivElement]'. If both your elements are DIVs, they will be converted into the same String value, which is why the second assignment overwrites the first one, i.e. both assignments assign to the same property.What you’re trying to achieve, cannot be implemented with a simple array.