Not only for this true for obj.hasOwnProperty(key) condition, but also one of the properties attributes called enumerable must be also set to true.
What about your code. Lets see what is buttons actually. You see that this is an object, which contains 7 properties. Only 4 properties in Chrome are shown, because they are enumerable
(function () {
"use strict";
var buttons = document.getElementsByClassName('remove');
console.log(buttons);
})();
<div>Some entry here
<button id="0" class="remove">Remove</button>
</div>
<div>Another entry here
<button id="1" class="remove">Remove</button>
</div>
So when you try to execute this code
(function () {
"use strict";
var buttons = document.getElementsByClassName('remove');
for ( var i in Object.keys( buttons ) ) {
console.log(i);
}
})();
<div>Some entry here
<button id="0" class="remove">Remove</button>
</div>
<div>Another entry here
<button id="1" class="remove">Remove</button>
</div>
it actually get's the indexes of the array returned from the Object.keys which are 1,2,3,4, but you don't have a property with name 2, 3, 4 in your buttons object. So why you get the error. Use forEach function to iterate over each property and add your event listeners.
(function () {
"use strict";
var buttons = document.getElementsByClassName('remove');
Array.prototype.forEach.call(buttons, button => {
button.addEventListener('click', function() {
this.parentElement.remove();
console.log(this.id);
});
});
})();
<div>Some entry here
<button id="0" class="remove">Remove</button>
</div>
<div>Another entry here
<button id="1" class="remove">Remove</button>
</div>
but below code returns 4 keysnope, 2 in firefox0and1the HTMLCollection has a collision between the index-based keys and id-based keys. I'm guessing that because the indexes are numbers Chrome is treating them as not equal to the string ids, thoughObject.keysis then converting them all to strings, so you end up with['0', '1', '0', '1'].Object.keys() == ["0", "1", "0", "1"]fordocument.getElementsByClassName('remove')- how special is that! - even with the above explanation, why would chrome be so wrong? (note, it has NOTHING to do with the id's being 0 and 1)for ( var i in Object.keys(Array.from(buttons)))- chrome doesn't mess that up