admin管理员组文章数量:1310868
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
-
1
You have to create the
<script>
element explicitly. Inserting it viainnerHTML
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
1 Answer
Reset to default 9You 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.
本文标签: javascriptHow to insert and execute script tag to the DOM using plain jsStack Overflow
版权声明:本文标题:javascript - How to insert and execute script tag to the DOM using plain js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741864553a2401824.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论