Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript getElementByID() not working [duplicate]

Why does refButton get null in the following JavaScript code?

<html> <head>     <title></title>     <script type="text/javascript">         var refButton = document.getElementById("btnButton");          refButton.onclick = function() {             alert('I am clicked!');         };     </script> </head> <body>     <form id="form1">     <div>         <input id="btnButton" type="button" value="Click me"/>     </div>     </form> </body> </html> 
like image 426
user366312 Avatar asked Dec 02 '09 00:12

user366312


People also ask

Can you use getElementById twice?

You can call getElementById multiple times and it will work.

Why is document getElementById not working?

This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element. The solution is that you need to put your JavaScript code after the closure of the HTML element or more generally before < /body > tag.

Should I use querySelector or getElementById?

You should opt to use the querySelector method if you need to select elements using more complex rules that are easily represented using a CSS selector. If you want to select an element by its ID, using getElementById is a good choice.


2 Answers

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html> <head>     <title></title>     <script type="text/javascript">         window.onload = function(){            var refButton = document.getElementById("btnButton");              refButton.onclick = function() {                 alert('I am clicked!');             }         };     </script> </head> <body>     <form id="form1">     <div>         <input id="btnButton" type="button" value="Click me"/>     </div>     </form> </body> </html> 
like image 132
jaywon Avatar answered Oct 07 '22 20:10

jaywon


You need to put the JavaScript at the end of the body tag.

It doesn't find it because it's not in the DOM yet!

You can also wrap it in the onload event handler like this:

window.onload = function() { var refButton = document.getElementById( 'btnButton' ); refButton.onclick = function() {    alert( 'I am clicked!' ); } } 
like image 36
Jacob Relkin Avatar answered Oct 07 '22 20:10

Jacob Relkin