getElementById returning null if it declares the script inside the head [duplicate]

0

I would like to know why when I make a console.log in my main.js, it returns null in the console, although, when I declare <script>main.js</script> inside the body, it returns the value of the id I'm looking for. Follow the script example 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>
    
asked by anonymous 29.12.2018 / 00:03

1 answer

1

I used the following statement:

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

});

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

  

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

See an example using document.addEventListener , notice that the returned value is not null, whereas the code that is outside the document.addEventListener returns the null value, and realizes that the order of the alerts is changed, since the document.addEventListener expects all or 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>
    
29.12.2018 / 01:02