Legend
Legend

Reputation: 13

changing display in an element of class by onclick method in javascript

These code don't work.

var x = document.getElementsByClassName("circle");
for (var i = 0; i < x.length; i++) {
    x[i].onclick = function(){ alert("hello!");};
}

Upvotes: 1

Views: 27

Answers (2)

A.Mostafa
A.Mostafa

Reputation: 98

Do it this way better:

for ( i = 0; i < x; i++) {
   x[i].addEventListener('click', function() { alert('Hello World') });
}

Upvotes: 0

Taki
Taki

Reputation: 17654

var x = document.getElementsByClassName("circle");
for (var i = 0; i < x.length; i++) {
  x[i].onclick = function() {
    this.style.opacity = 0
  };
}
.circle {
  width: 100px;
  height: 100px;
  background: red;
  border-radius: 50%;
  margin: 20px;
  float: left;
  transition: all .3s linear;
}
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>

Upvotes: 1

Related Questions