0

I have below code

<div class="test">Click Me</div>
<script>
document.getElementsByClassName('test').addEventListener('click', function(){
  alert('Hello world');
}, false);

Alert is not triggering. JS Fiddle: http://jsfiddle.net/ssod54fh/

foodiepanda
  • 128
  • 1
  • 14
  • 3
    Let's see how many minor variations on this exact same issue we can get posted here within a couple hours. Been at least 3 so far. –  May 04 '16 at 16:40
  • @squint At least it's not event delegation :p – Reinstate Monica Cellio May 04 '16 at 16:40
  • why negative votes, can anyone please explain? – foodiepanda May 04 '16 at 16:41
  • @suu It's not the most elegantly worded question, but I don't see why it deserves downvotes. If people have issues they should tell you so you can fix them. Some people are just mean. – Reinstate Monica Cellio May 04 '16 at 16:42
  • 1
    @squint I have duped more than 2 of them. But I got bored of doing that and answered it here. :p – Rajaprabhu Aravindasamy May 04 '16 at 16:42
  • 1
    @RajaprabhuAravindasamy: Yeah, I saw both of those. You've done your part. ;-) –  May 04 '16 at 16:44
  • I even searched for duplicates, but couldn't find as 'click' word is not in the duplicate one . lol . – foodiepanda May 04 '16 at 16:45
  • [site:stackoverflow.com javascript getelementsbyclassname addeventlistener doesn't work](https://www.google.com/search?num=50&q=site%3Astackoverflow.com+javascript+getelementsbyclassname+addeventlistener+doesn%27t+work&oq=site%3Astackoverflow.com+javascript+getelementsbyclassname+addeventlistener+doesn%27t+work) –  May 04 '16 at 16:47
  • 1
    @Archer: Doesn't take much research effort to find an answer to commonly asked questions like this. Hover your mouse pointer over the down arrow and you'll see it has *nothing* to do with being mean. –  May 04 '16 at 16:49
  • Yeah, it is. There's a high level of anonymous vindictiveness on this site, and anyone who says they don't know that is actually ignoring it because they're doing it themselves. Let's agree to disagree. – Reinstate Monica Cellio May 04 '16 at 16:51
  • 1
    @Archer: 1) You're assuming they're being vindictive. 2) You're accusing anyone of disagreeing with you of being vindictive. 3) It's unreasonable to suggest that anyone would have reason to be "vindictive" against a user that has only made 3 posts here. Not much opportunity to offend. So no, I won't agree to anything with someone throwing blanket accusations around at other users. –  May 04 '16 at 17:02

1 Answers1

1

Iterate over each elements and bind event to that,

[].forEach.call(document.getElementsByClassName('test'),function(elm){
 elm.addEventListener('click', function(){
  alert('Hello world');
 }, false);
});

Basically getElementsByClassName will return a nodeList. That means collection of node Object. node object has the function addEventListener in its prototype But not a nodeList.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130