Why my fiddle is not working as expected?
<button class="example"> Expirience </button>
var x = document.getElementsByClassName("example");
x.onClick = function() {
console.log('Hello')
}
Why my fiddle is not working as expected?
<button class="example"> Expirience </button>
var x = document.getElementsByClassName("example");
x.onClick = function() {
console.log('Hello')
}
var x = document.getElementsByClassName("example");
console.log(x)
x[0].addEventListener("click", function(){
console.log('Hello')
});
<button class="example"> Expirience </button>
getElementsByClassName returns an array.
var x = document.getElementsByClassName("example")[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>
var x = document.querySelector(".example");
x.addEventListener('click', function() {
console.log('Hello')
});
<button class="example"> Expirience </button>
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>