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"?
– Wictor Chaves
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.
– zHardy
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.
– Wictor Chaves
Put, it’s true, I forgot the scope. Thanks.
– zHardy
I’m finalizing an answer to explain better
– Wictor Chaves