Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

getElementsByTagName in JavaScript

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";
   };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...