Reputation: 36311
I am trying to get some event listeners to work, but for some reason they are not working properly.
The two event blocks below work fine on their own, but together only the removes
block works. If I comment out that block, then the users
block starts to work. What is causing this to happen?
var removes = document.getElementsByClassName("x");
for(var c in removes){
removes[c].addEventListener("click", function(){
console.log("Remove");
}, false);
}
var users = document.getElementsByClassName("user");
for(var i in users){
users[i].addEventListener("click", function(){
console.log("Go");
}, false);
}
Here is an example of the HTML:
<div class="user" data-id="123456">
<div>
<img id="avatar" src="http://example.com/photos/image.png" style="height: 50px;" alt="Avatar"/>
</div>
<div>
<h3>My Username</h3>
<p>[email protected]</p>
</div>
<div class="x" data-id="123456">×</div>
</div>
Upvotes: 2
Views: 146
Reputation: 69
getElementsByClassName returns a HTMLNodeList, which basicly is an Array of Nodes not an object on the form
{ "a": "b" }
So you don't use for ... in loops but a regular for
e.g.
for( var i = 0; i < removes.length; i++ ){
removes[i].addEventListener( "click", function(){} );
}
Upvotes: 4
Reputation: 18566
for(var c in removes)
will return you the properties of the HTMLNodeList.
For example:
If you run for(var i in removes) { console.log(i)}
you will get
length
item
namedItem
So instead use
for( var i = 0; i < removes.length; i++ ){
removes[i].addEventListener( "click", function(){console.log("Remove");
}, false} );
}
Upvotes: 1