3

How to insert any string like <script>console.log('it works');</script> into browser DOM and see "it works" in browser console then?

jQuery's append function doing the thing: $('html').append('<script>console.log('it works'); but I am looking for light solution, ideally plain js

context: the string can be complex like <div><h1>Title</h1></div><div><script>console.log('it works');</script></div> - it should renders correct in the DOM and do all the JS staff

3

1 Answer 1

9

You can use insertAdjacentHTML to insert the HTML, then go back and look for the scripts and copy the script src or text, and insert the copy into the DOM to run it:

// Sticking with broadly-supported features:
var htmlString = "<div><h1>Title</h1></div><div><script>console.log('it works');<\/script></div>";
var target = document.getElementById("target");
target.insertAdjacentHTML("beforeend", htmlString);
var scripts = target.getElementsByTagName("script");
while (scripts.length) {
    var script = scripts[0];
    script.parentNode.removeChild(script);
    var newScript = document.createElement("script");
    if (script.src) {
        newScript.src = script.src;
    } else if (script.textContent) {
        newScript.textContent = script.textContent;
    } else if (script.innerText) {
        newScript.innerText = script.innerText;
    }
    document.body.appendChild(newScript);
}
<div id="target"></div>

Note: Any inline document.write statements will not work as they would in the initial parse of a page; instead, they'll re-open the document and replace all of its content with whatever they write.

Sign up to request clarification or add additional context in comments.

1 Comment

Supplementary blog post regarding Element.insertAdjacentHTML method: hacks.mozilla.org/2011/11/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.