Reputation: 602
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
Upvotes: 3
Views: 5737
Reputation: 1074018
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.
Upvotes: 9