Get Off My Lawn
Get Off My Lawn

Reputation: 36311

getElementsByClassName doesn't seem to work

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">&times;</div>
</div>

Upvotes: 2

Views: 146

Answers (2)

user3597525
user3597525

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

mohamedrias
mohamedrias

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

Related Questions