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?