Search code examples
javascriptes6-modules

Any (optimal) way to get DOM element of a script module from the module?


I have the following:

<script type="module">

// some code here to get the <script>'s DOM reference

</script>

Is it possible?

There could be any number scripts like that. I'd like to insert HTML after the script without an explicit reference.


Solution

  • You can use a classic <script> to define some globals and then rely on the fact that <script type="module">'s defer by default, meaning they will execute in order after all the document has been fully parsed, but before DOMContentLoaded has fired.

    This code is only meant to give you a general idea of how you can do this without providing explicit identifiers to your script tags via some data- attribute that you could then run document.querySelector on.

    Example repo on GitHub.

    NOTE: You should just copy/paste what is in the snippet and run against a web server to see it work, or see it on GitHub pages. I think the snippets environment is not fully supportive of ES modules.

    <!DOCTYPE html>
    <html>
        <head>
            <title></title>
        </head>
        <body>
            <script>
                var counted = 1
                var script = null
            </script>
            <p>content before first module script</p>
            <script type="module">
                script = document.scripts[counted++]
                script.insertAdjacentHTML('afterend', `<p>inserted after ${counted - 1} module script</p>`)
            </script>
            <p>content after first module script</p>
            <script type="module">
                script = document.scripts[counted++]
                script.insertAdjacentHTML('afterend', `<p>inserted after ${counted - 1} module script</p>`)
            </script>
            <p>content after second module script</p>
            <script type="module">
                script = document.scripts[counted++]
                script.insertAdjacentHTML('afterend', `<p>inserted after ${counted - 1} module script</p>`)
            </script>
            <p>content after third module script</p>
        </body>
    </html>