-2

I'm using insertAdjacentHtml to create a div with a button right after the opening body tag of the page.

<script>document.addEventListener('DOMContentLoaded', function(){
            var code = '<div class="overlay"><button class="overlay-close"></button></div>';
            document.body.insertAdjacentHTML('afterbegin', code);
        }, false);</script>

But I get an error with the querySelector on my closeBttn.

Uncaught TypeError: Cannot read property 'querySelector' of null

<script>
        (function() {
            var overlay = document.querySelector( 'div.overlay' ),
                closeBttn = overlay.querySelector( 'button.overlay-close' );
                /* irrelevent other code here */
        })();
</script>

Clearly it looks like I have the overlay button and overlay div present, but it still not working. It works fine without using insertAdjacentHTML, but once I wrapped my code in this function, I get the error, so I'm thinking there's something going on here when I use this function to create my div.

Can anyone help to debug or give a work around?

kevinkt
  • 675
  • 10
  • 20
  • When is the second piece of code being run? Your error would indicate to me that the code is being run *before* DOMContentLoaded, so no div.overlay exists in the body. – Liam Egan Aug 15 '16 at 01:37
  • @LiamEgan Thanks you were right. It worked after adding this: (document.addEventListener("DOMContentLoaded",function() { var overlay = document.querySelector( 'div.overlay' ), – kevinkt Aug 15 '16 at 01:44

1 Answers1

0

The code was loading before DomContentLoaded so I changed my code to the following:

<script>
        (document.addEventListener("DOMContentLoaded",function() {
            var overlay = document.querySelector( 'div.overlay' ),
                closeBttn = overlay.querySelector( 'button.overlay-close' );
                /* irrelevent other code here */
        }));
</script>
kevinkt
  • 675
  • 10
  • 20