getElementsByTagName in JavaScript [duplicate]

I'm new to the syntax of pure JavaScript; Do you know why "getElementsByTagName" is not working in my simple test:

 var btn = document.getElementsByTagName('button');
console.log(btn);


btn.onclick=function(){
    alert('entered');
document.getElementById("demo").innerHTML="test";
}

Fiddle


getElementsByTagName returns an array, not a single element. You need to loop through your results and attach a function to each one individually, something like this:

var buttons = document.getElementsByTagName('button');

for( var x=0; x < buttons.length; x++ ) {

   buttons[x].onclick = function(){

       alert('entered');
       document.getElementById("demo").innerHTML="test";
   };
}