Home >Web Front-end >JS Tutorial >Why Don't Scripts Execute When Using .innerHTML, and How Can I Fix It?

Why Don't Scripts Execute When Using .innerHTML, and How Can I Fix It?

DDD
DDDOriginal
2024-12-14 17:37:11775browse

Why Don't Scripts Execute When Using .innerHTML, and How Can I Fix It?

Executing Inserted <script> Elements with .innerHTML</script>

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.</script>

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.</script>

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.</script>

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);
  });
}

To use this solution, simply replace the current .innerHTML assignment with a call to setInnerHTML. The updated code would look like:

.innerHTML = HTML;    // does *NOT* run `<script>` tags in HTML
setInnerHTML(<🎝🎝🎝>, HTML); // does run `<script>` tags in HTML</script>

The above is the detailed content of Why Don't Scripts Execute When Using .innerHTML, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn