简体   繁体   中英

Why can't my javascript code in the head selection get an element?

I have been working on a pi calculator in javascript for a long time now and I have finally finished. The problem is that my script in the head section:

document.getElementById("button").addEventListener('click', (function(){
    alert('Beginning…');
}), false);

And I have this in my body section:

<input type="button" id="button" value="Calculate!!"/>

But when I open the webpage, I get the following error: "null is not an object, evaluating document.getElementById("button").addEventListener"

Does anyone know why my code isn't functioning properly?

Thank you.

Wrap it on a window onload event:

window.onload = function()
{
    document.getElementById("button").addEventListener('click', (function(){
        alert('Beginning…');
    }), false);
};

or

window.addEventListener('load', function()
{
    document.getElementById("button").addEventListener('click', (function(){
        alert('Beginning…');
    }), false);
});

or, if your script doesn't have to be in the head, put it after the element that has the id of button.

DEMO

Javascript gets executed ass soon as possible, so when it's in the head tag, the document hasn't fully loaded. you can have your code run when the document is ready by using the load even

window.addEventListener("load", function(){
    /*your code here*/
});

I guess window is supposed to be the proper way to do it, even though one would think document.load would be there ("When the document loads, do this" instead of "when the window loads do this") or run your code at the end of the body. You can still have all your methods in the head.

You have two options:

  1. Wrap your code in a window.onload event.
  2. Place your <script></script> at the bottom of the body right before </body> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM