Why is an HTML element found only in "onload"?

Asked

Viewed 36 times

2

If I put the code free, without being inside the onload, the variable button flipped null. My current code works, but I wanted to know why it doesn’t work without being inside the function onload.

HTML

<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="./script.js"></script>
    </head>

    <body>

        <h1 id="title">Title</h1>
        
        <input id="start" type="submit" value="Start">

    </body>
</html> 

Javascript

onload = function() {
    let h1 = document.getElementById("title"); 
    let button = document.getElementById("start");

    button.addEventListener("click", changeTitleText);
        
    function changeTitleText() {
        h1.innerHTML = "New Title"
    }
}

Este é o erro que ocorre se eu colocar o código JavaScript acima fora da função Onload

  • It’s not just after load. In fact, it works because the load will always be fired after DOMContentLoaded, which is the event that marks, in fact, the moment when the GIFT can be manipulated.

2 answers

2

Out of onload the code is executed before the element <button>exist. Within the onload you ensure that the code will run only when the entire page is loaded.

Therefore it is recommended to put the scripts at the end of the page, before closing </body>

1

Several actions occur when loading a page on the internet. HTML is downloaded, understood and rendered by the browser; images and style sheets are downloaded and rendered; etc. With Javascript you can execute code that is linked to these actions, called events.

The event of load, in question, it is triggered at the end of the loading of the HTML document. It is at this point that you have the assurance that everything is in the DOM, all images, scripts, links, and subframes loaded. Without the event, you can’t be sure that what you need is already there when your code runs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.