-4

I'm trying to use function closure in my javascript as follows:

In my html file:

<head>
    <script src="myscript.js"></script>
</head>

<body>
    <section id="mysectionId"></section>
</body>

In myscript.js:

(function() {
    var id = document.getElementById('mysectionId');
    console.log(id);
}());

However, id seems to equal null. I'm not sure what I've done wrong - does function closure scope exclude globals like 'document'? If so, how come I can still use 'console.log()' inside the function closure?

user12066
  • 613
  • 6
  • 23
  • Those two lines run right away, before `
    ` exists.
    –  Oct 24 '19 at 20:43
  • 1
    This is nothing to do with a closure. 1. You have an extra `)` in your code. 2. How are you executing this? Have a look at [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) – VLAZ Oct 24 '19 at 20:43
  • @VLAZ: extra parenthesis fixed – user12066 Oct 24 '19 at 20:47

1 Answers1

-2

You're javascript is running before your html loads. Put your script tag after your html content at the very bottom of the body

<head>
    // put css here
</head>

<body>
    <section id="mysection"></section>
<script src="myscript.js"></script>
</body>
Max Baldwin
  • 3,404
  • 3
  • 26
  • 40