Home >Web Front-end >JS Tutorial >How Can I Ensure Scripts Execute When Using `innerHTML` in JavaScript?
Executing Scripts Inserted with .innerHTML
Inserting content into an element using innerHTML can encounter issues where scripts within the inserted content do not execute. While solutions using jQuery or eval exist, here's a snippet of code that addresses this issue using pure JavaScript:
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); }); }
This function takes an element and HTML string as parameters. It replaces the element's innerHTML with the provided string and iterates over any script elements within the HTML. For each script element, it creates a new one with the same attributes and script text. Finally, it replaces the old script element with the new one.
To use this function, simply set an element's innerHTML:
.innerHTML = HTML; // does *NOT* run <script> tags in HTML setInnerHTML(, HTML); // does run <script> tags in HTML
The above is the detailed content of How Can I Ensure Scripts Execute When Using `innerHTML` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!