Michelangelo
Michelangelo

Reputation: 5948

Addeventlistener in for loop works, but debugger throws me an uncaught TypeError: Cannot read property 'addEventListener' of undefined

So my code works as I want, but most (except IE) debuggers throw me this error:

uncaught TypeError: Cannot read property 'addEventListener' of undefined

This is the code:

//Get all elements with the class 'order' and attach eventlisteners

var products=document.getElementsByClassName('order');
for (i=0; i<=products.length; i++){ 
if (products) {
    products[i].addEventListener('keyup', delegate(), false);
    products[i].addEventListener('click', delegate(), false);
    };

}

function delegate(){
    return function(){
        ch();
    }
}

This code is within the window.onload! I don't worry to much about this error, because my code works perfectly. I am still a junior coder and I would really like to understand why this happens. Also, I have tried closures and they work but the error still exists. So please don't refer to any javascript closure articles!

My question: is my code somehow wrong or are the debuggers sensitive?

Thanks in advance.

Upvotes: 0

Views: 255

Answers (1)

Kevin Lab&#233;cot
Kevin Lab&#233;cot

Reputation: 1995

The error is thrown during your last iteration. If products.length is 8 (for example), the valid indexes are 0 to 7. Your code also uses 8 as an index. You must exclude the last one. Just update your for to iterate to i<products.length instead of i<=products.length.

//Get all elements with the class 'order' and attach eventlisteners

var products=document.getElementsByClassName('order');
for (i=0; i<products.length; i++){ 
if (products) {
    products[i].addEventListener('keyup', delegate(), false);
    products[i].addEventListener('click', delegate(), false);
    };

}

function delegate(){
    return function(){
        ch();
    }
}

Upvotes: 1

Related Questions