getElementById returning null if declaring the script inside the head

Asked

Viewed 89 times

0

I wonder why when I make one console.log in my main.js, returns null in the console, though, when I declare the <script>main.js</script> inside the body, it returns the id value I’m looking for. Follow the example with script inside the head.

(function(win, doc){
    'use strict';

    console.log(document.getElementById('text-link'));

    
})(window, document);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="main.js"></script>
    
</head>
<body>
	<a id="test-link" >text</a>
    
</body>
</html>

  • You put the body script at the bottom of the "a"?

  • Yes. I put it, and I saw that it worked. I want to understand why it doesn’t work when I put it there in the head, below the meta tag.

  • is because html is loading from top to bottom, so putting on top, it loads the script, but the "a" still does not exist, since it is below, for your script to work, you have to put something for it to wait for all html to load.

  • Put, it’s true, I forgot the scope. Thanks.

  • I’m finalizing an answer to explain better

1 answer

1


I used the following instruction:

document.addEventListener("DOMContentLoaded", function(event) {

});

This way, all the code inside the keys will only be executed after all the html is already loaded.

Another problem I found was the following in your code Javascript this written text-link and in your html is with the id test-link.

See an example using document.addEventListener, realize that the value returned is not null, while the code is outside the document.addEventListener returns the null value, and realizes that the order of the Alerts are exchanged, since the document.addEventListener expects all html to load.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script>
      document.addEventListener("DOMContentLoaded", function(event) {
          alert(document.getElementById('test-link'));
      });
    </script>
    <script>
      alert(document.getElementById('test-link'));
    </script>
</head>
<body>
	<a id="test-link" >text</a>
</body>
</html>

Browser other questions tagged

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