How to run script elements inserted with innerHTML with JavaScript?

Sometimes, we want to run script elements inserted with innerHTML with JavaScript

In this article, we’ll look at how to run script elements inserted with innerHTML with JavaScript.

How to run script elements inserted with innerHTML with JavaScript?

To run script elements inserted with innerHTML with JavaScript, we append the script element to the body element.

For instance, we write

const script = document.createElement("script");
script.innerHTML = 'console.log("hi")';
document.body.appendChild(script);

to create a script element with createElement.

Then we call document.body.appendChild to append the script element as the last child of the body element and run it.

Conclusion

To run script elements inserted with innerHTML with JavaScript, we append the script element to the body element.