Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the code I’ve in JavaScript: 

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

console.log(btn);


 

btn.onclick=function(){

    alert('entered');

document.getElementById("demo").innerHTML="test";

}

But “getElementsByTagName” is not working. Can anyone tell me what I’m doing wrong here? 

1 Answer

0 votes
by (19.7k points)

Use the below code:

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

This returns an array of matched elements. The ‘0’ index to access the button. 

You can also specify ID on button by this getElementById() like below:

JS: 

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

HTML: 

<button id="myButton">....</button>

Interested in Java? Check out this Java Certification by Intellipaat. 

Related questions

0 votes
1 answer
asked Jun 8, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked May 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked May 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
0 votes
1 answer
asked May 7, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...