Executing Inserted Elements with .innerHTML</h2> <p>When injecting content containing <script> tags into an element using .innerHTML, the scripts often fail to execute. This issue arises due to the inherent nature of .innerHTML, which inserts static HTML, preventing browsers from automatically evaluating scripts within it.</p> <p>To address this problem, a solution involves manipulating the injected HTML directly, creating a dynamic process that mimics the browser's default behavior for <script> elements.</p> <p>One approach, written in ES6, focuses on using pure JavaScript, without external libraries or complicated DOM modifications. It iterates through all <script> elements in the injected content, creating new elements with the same attributes and text content.</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre>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); }); }</pre><div class="contentsignin">Copy after login</div></div> <p>To use this solution, simply replace the current .innerHTML assignment with a call to setInnerHTML. The updated code would look like:</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre>.innerHTML = HTML; // does *NOT* run `<script>` tags in HTML setInnerHTML(, HTML); // does run `<script>` tags in HTML</pre><div class="contentsignin">Copy after login</div></div>