最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to insert and execute script tag to the DOM using plain js - Stack Overflow

programmeradmin0浏览0评论

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 plex 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

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 plex 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

Share Improve this question edited Jul 18, 2019 at 11:37 Max Vorozhcov asked Jul 17, 2019 at 15:38 Max VorozhcovMax Vorozhcov 6021 gold badge7 silver badges22 bronze badges 3
  • 1 You have to create the <script> element explicitly. Inserting it via innerHTML will intentionally not work as defined by the spec. – zero298 Commented Jul 17, 2019 at 15:40
  • See script tag create with innerHTML of a div doesn't work. – zero298 Commented Jul 17, 2019 at 15:41
  • Possible duplicate of script tag create with innerHTML of a div doesn't work – zero298 Commented Jul 17, 2019 at 15:41
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论