-1

Why my fiddle is not working as expected?

<button class="example"> Expirience </button>



var x = document.getElementsByClassName("example");

x.onClick = function() {
  console.log('Hello')
}

https://jsfiddle.net/xrkjvt57/18/

MountainConqueror
  • 592
  • 3
  • 7
  • 27

5 Answers5

3

var x = document.getElementsByClassName("example");
console.log(x)

x[0].addEventListener("click", function(){
console.log('Hello')
});
<button class="example"> Expirience </button>
Emeeus
  • 5,072
  • 2
  • 25
  • 37
2

getElementsByClassName returns an array.

var x = document.getElementsByClassName("example")[0];
0

There are a couple of problems with your code, here is a working example with comments as to what was wrong.

var x = document.getElementsByClassName("example");

// x is an array, you need to loop over the elements in the array
for(var i =0; i < x.length; i++)
  // onClick is not how you add a click handler, use addEventListener and 'click'
  x[i].addEventListener("click", function() {
    console.log('Hello')
  });
.example {
  color: red;
}
<button class="example"> Expirience </button>
Adam H
  • 1,750
  • 1
  • 9
  • 24
0

    var x = document.querySelector(".example");

    x.addEventListener('click', function() {
      console.log('Hello')
    });
<button class="example"> Expirience </button>
zanmato
  • 102
  • 1
  • 7
0

x is a NodeList of elements, so you have to loop over them and handle each one individually. In addition, the event handler is all lowercase (onclick). You want:

var buttons = document.getElementsByClassName("example");

Array.prototype.forEach.call(buttons, function (button) {
 button.onclick = function() {
       console.log('Hello');
 }
})
<button class="example"> Expirience </button>
Aankhen
  • 2,198
  • 11
  • 19