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.