Onclick function in the – ericmp Sep 13 '22 at 07:28

  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Ivar Sep 13 '22 at 07:31
  • 1 Answers1

    3

    You need to use defer or move the script tag to the end of the body.

    <!DOCTYPE html>
    <html>
        <head>
            <script>
            document.addEventListener('DOMContentLoaded', () => {
             const btn = document.getElementById("mainButton");
            btn.onclick = function(){
                alert("You shouldn't have clicked this button!");
            };
            });
           
        </script>
        </head>
        <body>
            <button id="mainButton">Do not click this button</button>
            
        </body>
    </html>

    <!DOCTYPE html>
    <html>
        <head>
           
        </head>
        <body>
            <button id="mainButton">Do not click this button</button>
             <script>
            const btn = document.getElementById("mainButton");
            btn.onclick = function(){
                alert("You shouldn't have clicked this button!");
            };
        </script>
        </body>
    </html>
    mgm793
    • 1,968
    • 15
    • 23
    • This is a [_very_ commonly asked question](https://stackoverflow.com/questions/linked/14028959?lq=1). Please don't answer those as per [answer]. Instead, flag them to be closed as [a duplicate](https://stackoverflow.com/help/duplicates). – Ivar Sep 13 '22 at 07:33
    • Thanks, it works! I somehow forgot that you would have to write the script after the tag has been declared, otherwise it wouldn't exist at the time of execution. – Snip Sep 13 '22 at 07:33