Search code examples
javascriptdomappendchild

How to append a raw JavaScript tag to document.body without jQuery


I get a raw JavaScript tag from the server:

"<script>alert('hi');</script>"

Now, I need to append it to <body> so that it fires. I can't simply create a new script element, because this string already contains the <script> part. Is there something analogous to

child = document.createElementFromHTML("<script>alert('hi');</script>");
document.body.appendChild(child)

Thanks for any help.

EDIT

Here's why it's not a duplicate, hall monitors:

If you set the inner html of a div to be a script it won't fire. I need to append an element generated from only text to the body.

EDIT 2

final solution:

window.onload = function() {
document.body.innerHTML += "<script>alert('hi');</script>";
var script = document.scripts[document.scripts.length - 1];
var s = document.createElement("script");
s.textContent = script.textContent;
document.body.removeChild(script);
document.body.appendChild(s);
}

Solution

  • You can concatenate document.body.innerHTML with <script> html string, get .textContent of last script in document, create script element, set script element .textContent to value retrieved from concatenated html <script> string, remove last <script>, append new <script> to document.body.

    <script>
      document.body.innerHTML += "<script>alert('hi');<\/script>");
      var script = document.scripts[document.scripts.length - 1];
      var s = document.createElement("script");
      s.textContent = script.textContent;
      document.body.removeChild(script);
      document.body.appendChild(s);
    </script>