document.getElementById("someI...">

GetElementById and null - why?

Why is this code not working? I am using FF.

<head> <script type="text/javascript"> document.getElementById("someID").onclick = function(){ alert("Yahooo"); } </script> </head> <body> <a href="#" id="someID">someID</a> </body> </html> 

I get javascript error getElementById is zero.

+6
source share
2 answers

The required DOM does not load when the script is executed. Either move it down (below href), or define it as follows:

 window.onload = function () { document.getElementById("someID").onclick = function(){ alert("Yahooo"); } } 

window.onload will be called when the page is fully loaded.

+10
source

Since this element does not yet exist when the script is executed, the document has not yet been displayed. Either run the script in the script block after the corresponding HTML code, or use the "document on ready" event handler - preferably from something like jQuery .ready() or native window.onload .

+2
source

Source: https://habr.com/ru/post/905989/


All Articles