javascript - Object.keys() returns properties -
from this answer said object.keys() properties defined on object (the ones return true obj.hasownproperty(key) below code returns 4 keys , producing error confusing me.
(function () { "use strict"; var buttons = document.getelementsbyclassname('remove'); console.log("no of keys: ", object.keys(buttons).length); ( var in object.keys( buttons ) ) { buttons[i].onclick = 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> how in javascript?
so here's how you'd loop on buttons original code using for loop:
(function () { "use strict"; var buttons = document.getelementsbyclassname('remove'); console.log(buttons); (var index = 0 ; index < buttons.length ; ++index) { buttons[index].onclick = function() { this.parentelement.remove(); console.log(this.id); }; } })(); <div>some entry here <button id="a" class="remove">remove</button> </div> <div>another entry here <button id="b" class="remove">remove</button> </div> note buttons object htmlcollection. exposes elements both index , id. in original example ids 0 , 1, quite confusing in case because causes them clash indexes. object.keys(buttons) returning ['0', '1', '0', '1'], bit odd, presumably because of number/string shenanigans. i've changed ids in example a , b object.keys(buttons) ['0', '1', 'a', 'b'].
Comments
Post a Comment