0

I am pretty new to JavaScript so I don't know the ins and outs of the language but I do have some knowledge of it. I created a self invoked function that would sort an array of zip-codes and then output it to a div element in the html file.

Unfortunately, the output isn't going into the div element because the function is executed before the html elements is ready, therefor it doesn't exist.

Is there anyway that I could access the div element within the function without having to use Window.Load, etc?

Thank you! click on the link below to view my function.

Screenshot of function

J Yang
  • 17
  • 2
  • 1
    Add the script at the bottom of the tag instead of at the top – Jorg Feb 12 '18 at 04:33
  • You can move your ` – blurfus Feb 12 '18 at 04:34
  • Possible duplicate of [TypeError: getElementById is null](https://stackoverflow.com/questions/24972488/typeerror-getelementbyid-is-null) – blurfus Feb 12 '18 at 04:37
  • @ochi How is that post even relevant? – Nate Feb 12 '18 at 04:39
  • Take a look at [this](https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery) – Rusty Feb 12 '18 at 04:40
  • 1
    You should add the relevant code no a screenshot See: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve) – Satpal Feb 12 '18 at 04:40
  • @Nate did you read it? it's the same issue: trying to invoke a call to `getElementyById(...)` before the element is rendered into the DOM - the solution suggested is the same in both: move your JS to the end of the body tag – blurfus Feb 12 '18 at 04:41

2 Answers2

0

Is there anyway that I could access the div element within the function without having to use Window.Load, etc?

Just move that code to the end of your html - after elements in question. For example after </body>

c-smile
  • 24,546
  • 7
  • 54
  • 79
0

From what I know, you can't access the DOM if it doesn't exist in that moment.

I know I know, don't use window.onload. But I assure you this is different than waiting for the DOM to load and then follow up with your calculations.

You can have a function evaluate something, then actually hang on the result and wait, and then finally fill the innerHTML when the DOMContentLoaded event has fired... or perhaps something of similar flavour, have a look at this.

<script>
    const calculations = (function () {
        // Super smart calculations...

        var output = "Result of smart calculations";

        function findWhereOutputGoes() {
            return document.getElementById('output-div');
        }

        return {
            output: output,
            findWhereOutputGoes: findWhereOutputGoes,

        }
    })();

    document.addEventListener('DOMContentLoaded', function(){ // Fires as soon as DOM has loaded
        calculations.findWhereOutputGoes().innerHTML = calculations.output;
    });
</script>
<div id="output-div">

</div>
Florian Suess
  • 197
  • 2
  • 6