0

I was trying to alert the number of clicks this div gets. But something is wrong. I am able to alert when using getElementById. I wanted just the shape to invoke the click counter. So I used getElementsByClassName to invoke the function clickCounter. But what I'm doing is not working ie, it's not giving the alert.

Where did I go wrong? Also just Pure JavaScript (Vanilla JS) only.

var count = 0;

function clickCounter(){
 count++;
 alert(count);

}

function initMyEvents(){
 document.getElementsByClassName("clicked").onclick = clickCounter;
}

window.onload = initMyEvents;
:root {
  --main-hand-color: #fb7a7a;
  --main-shirt-color: #3d4886;
}

.box{
 width: 500px;
 height: 500px;
 margin: auto;
 position: relative;
 display: block;
 margin-top: 5%;
}

.shirt{
 position: absolute;
 height: 350px;
 width: 100px;
 background-color: var(--main-shirt-color);
 top: 0%;
 left: 0;
}

.wrist{
 position: absolute;
 height: 300px;
 width: 435px;
 background-color: var(--main-hand-color);
 border-radius: 10%;
 top: 5%;
 left: 0;
 z-index: -1;
}

.thumb{
 position: absolute;
 height: 250px;
 width: 100px;
 background-color: var(--main-hand-color);
 border-radius: 20%;
 top: 45%;
 left: 28%;
}
<div class="box">
  <div class="shirt clicked"></div>
  <div class="wrist clicked"></div>
  <div class="thumb clicked"></div>
 </div>
Remix Protocol
  • 77
  • 2
  • 10
  • `getElementsByClassName` returns an array of elements, not a singular element. You'll probably want a `for` loop or `.forEach` in there to add the listener to each element found. Or just do `.getElementsByClassName('clicked')[0]` to add the handler on the first .box found. – cbr May 18 '20 at 16:25
  • You may be wondering why you didn't get an error, given the answers to the [linked question](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) pointing out that `getElementsByClassName` doesn't return an element, it returns an `HTMLCollection`. The reason is that most JavaScript objects let you add properties to them through simple assignment, and `HTMLCollection` (although it's a DOM object) allows that too. So the assignment worked, it's just that ithe function that got assigned wasn't used for anything. – T.J. Crowder May 18 '20 at 16:26

0 Answers0