0

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

Dairo
  • 822
  • 1
  • 9
  • 22

4 Answers4

1

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";
   };
}
Cody O'Dell
  • 181
  • 6
0

Should be

var btn = document.getElementsByTagName('button')[0];

instead of

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

getElementsByTagName returns array of matched elements. So use 0 index to access the button.

More about getElementsByTagName()

OR

You can provide the specific id on button and can use getElementById()

JS

var btn = document.getElementById('myButton');

HTML

   <button id="myButton">....</button>
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
0
getElementsByTagName()

returns an array, which you have to access by their index.

For selecting a single element, use getElementById('id here');

The method itself says get Elements.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

Just replace btn by btn[0] like this-

   btn[0].onclick=function(){
     alert('entered');
     document.getElementById("demo").innerHTML="test"; 
   }
Mandeep Singh
  • 983
  • 8
  • 9