Abraham Brookes
Abraham Brookes

Reputation: 2007

Calling incrementer from a for in loop

I'm having a bit of trouble calling the incrementer i in this loop in order to identify my current element. Firebug gives me the error "li[i].addEventListener is not a function".

document.addEventListener("DOMContentLoaded", function(){

var li = document.getElementsByTagName('li');

for(var i in li){
    li[i].addEventListener('click', function(){
        alert('yey');
    });
    }
});

The strange thing is if I call

alert(li[i].getAttribute('id')

I get the id alerted to me, but if I then use

var id=li[i].getAttribute('id');
document.getElementById(id).addEventListener(blah);

I get the same "is not a function" error. Is this a for in loop thing? I noticed that alert(i); called some extra stuff at the end of the loop, so is there a different way to use the incrementer in a for in loop? By the way the list I am using is thus:

<ul>
    <li id=pomp>
        stuff
    </li>
    <li id=and>
        and
    </li>
    <li id=circumstance>
        things
    </li>
</ul>

Upvotes: 0

Views: 91

Answers (3)

Alnitak
Alnitak

Reputation: 339975

As @lbu has pointed out, you should be using for (decl; test; inc) to iterate through an array.

However this is also a good place to use delegation, since every <li> must be a direct descendent of a <ul>, you can put the event handlers there instead, and give your browser less work to do:

var ul = document.getElementsByTagName('ul');

for (var i = 0, n = ul.length; i < n; ++i) {
    ul[i].addEventListener('click', function(ev) {
        alert(ev.target.id);
    });
}

See http://jsfiddle.net/2mk3w/

Upvotes: 0

Varun Achar
Varun Achar

Reputation: 15109

Try it this way

for(var i in li){
    i.addEventListener('click', function(){
        alert('yey');
    });
    }
});

Upvotes: -1

Ibu
Ibu

Reputation: 43850

That is why you have to avoid using for in loop

for(var i=0;i<li.length;i++){
    li[i].addEventListener('click', function(){
        alert('yey');
    });
}

when you use for in, i is not an integer like you expect, instead it is a property of the nodelist.

Upvotes: 3

Related Questions