-1
Uncaught TypeError: Object 0 has no method 'addEventListener' 

var A={};
A.addEventsToClassName=function(event,className,func)
{
    var a=document.getElementsByClassName(className);
    for(var b in a)
        {
            b.addEventListener(event,func,false);
        }
};

Object b is meant to be an element object once the function is called later in the code. How can I prevent this error?

Amauri
  • 540
  • 3
  • 15
  • 1
    How's about you upvote/accept on the [question you just asked? ](http://stackoverflow.com/q/22649724/1216976) – SomeKittens Mar 26 '14 at 01:55

3 Answers3

0

A for (var b in a) will give the property names within a, not the actual values; so you need to dererefence a when you want to use them.

a[b].addEventListener(event, func, false);

Also, it's an Array like data structure, so you should iterate it as such:

for (var i = 0; i < a.length; ++i) {
    a[i].addEventListener(event, func, false);
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

b is not an object nor an element, it is a string ("0"). for...in gives you the keys not the value.


Don't use for(var b in a) to loop through a NodeList (it will loop through not only the properties of itself but also the properties inherited from its parent), do this instead:

for(var i = 0; i < a.length; a++){
    a[i].addEventListener...
}

If you ask why, then take this for example,

for(var a in document.querySelectorAll("body")){
    console.log(a);
}

>"0"
>"length"
>"item"

You can see that for...in does not work in this case since length and item are not actually in the list but still properties inherited.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

The b is probably a index not your object . Perhaps you want write like this:

a[b].addEventListener(event,func,false);
zzy
  • 1,771
  • 1
  • 13
  • 48
  • @Derek朕會功夫 what do you mean the undefined? The a[b] ? The b is index or key in object a , so I think a[b] is defined. – zzy Mar 26 '14 at 02:16
  • There is a [`namedItem` method](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection#Methods) which makes it to throw this error. In `HTMLCollection.namedItem.addEventListener`, `addEventListener` does not exist in `HTMLCollection.namedItem`. – Derek 朕會功夫 Mar 26 '14 at 02:18
  • @Derek朕會功夫 yeah ,I understand.But we don't know the context and environment , perhaps the addEventListener is exist :-) – zzy Mar 26 '14 at 02:39