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>