0

I have to place a script in the head that creates a DIV element and inserts this DIV into the body tag.

var condiv = document.createElement("div");
(condiv.innerHTML = " "),
    condiv.setAttribute("class", "ads"),
    document.body.appendChild(condiv),
    0 === condiv.offsetHeight ||
        (function () {

        }

The script works when I insert it into the body but not before. Is there a way to add the DIV into the body when the script is located into the head (before) with pure javascript and not Jquery? Its very important to have it in the head, because I have to place it before other scripts in the head and I dont want to have this scripts in the body. I know, I could use document.head.appendChild but HTML elements in the head are not validate. Thank you for your time.

Lars Vegas
  • 221
  • 2
  • 10
  • It's probably not working because the code is executing before the body has loaded, You can wrap the code inside a [DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) event. This will wait until your page is ready before executing. – Reyno Sep 21 '20 at 09:20
  • thank you. What is with scripts in the body? With domcontentloaded this script will execute before my code runs, correct? – Lars Vegas Sep 21 '20 at 09:23
  • It worked once I added a parenthesis at the end and put the code in `addEventListener('load', ()=>{ /* in here */ });`. Of course, I'm pretty sure you don't know what the comma operator does. – StackSlave Sep 21 '20 at 09:26

1 Answers1

0

Since the script is in the head section and is loaded before the body tag is created you won't find the body tag to place a DIV in it. There are multiple ways you can wrap your script so that it would run after the DOM is loaded. Each with a nuance difference to it. You can see examples of them at MDN. Basically, you can load this code by writing it in this function and it would load after all the page is loaded (including images and other scripts):

window.addEventListener('load', (event) => {
   var condiv = document.createElement("div");
   (condiv.innerHTML = " "),
      condiv.setAttribute("class", "ads"),
      document.body.appendChild(condiv),
      0 === condiv.offsetHeight ||
          (function () {

          }
});

there are ways to load it after only the DOM is loaded that are elaborated in this question I think the answers over there would be even better for your use.

Saar Davidson
  • 1,312
  • 1
  • 7
  • 16