How to Execute Scripts Inserted Using innerHTML?
When using innerHTML to inject content into an element, scripts included within the content may not be executed automatically. This occurs because browsers don't evaluate scripts after they're inserted using innerHTML.
Solution:
To resolve this, you can use JavaScript to recreate each script element manually and replace the original script tags in the DOM. Here's a solution in ES6:
function setInnerHTML(elm, html) { elm.innerHTML = html; Array.from(elm.querySelectorAll("script")) .forEach(oldScriptEl => { const newScriptEl = document.createElement("script"); Array.from(oldScriptEl.attributes).forEach(attr => { newScriptEl.setAttribute(attr.name, attr.value); }); const scriptText = document.createTextNode(oldScriptEl.innerHTML); newScriptEl.appendChild(scriptText); oldScriptEl.parentNode.replaceChild(newScriptEl, oldScriptEl); }); }
Usage:
.innerHTML = HTML; // does *NOT* run <script> tags in HTML setInnerHTML(, HTML); // does run <script> tags in HTML
The above is the detailed content of Why Don't Scripts in innerHTML Execute, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!