0

Hey guys could anyone explain why the event doesn't execute? The debugger doesn't give any error at all! Thank you in advance

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>

  <button class="boton">prueba</button>
  <body>

<script type="text/javascript">

var elemento= document.getElementsByClassName("boton")
elemento.onclick=function(){
  alert("hola");
};
debugger;

</script>

  </body>
</html>
JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

1 Answers1

1

The DOM method document.getElementsByClassName() returns an array. You must loop through the array items before assigning the onclick handler:

var elemento = document.getElementsByClassName("boton")
for (var i = 0; i < elemento.length; i++) {
  elemento[i].onclick = function() {
    alert("hola");
  };
}
debugger;
<button class="boton">prueba</button>

Alternatively, if you are selecting only one element, you can use document.querySelector():

var elemento = document.querySelector(".boton");
elemento.onclick = function() {
  alert("hola");
};
debugger;
<button class="boton">prueba</button>
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36