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

Why Don't Scripts in innerHTML Execute, and How Can I Fix It?

Linda Hamilton
Release: 2024-12-20 12:43:17
Original
887 people have browsed it

Why Don't Scripts in innerHTML Execute, and How Can I Fix It?

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);
    });
}
Copy after login

Usage:

.innerHTML = HTML; // does *NOT* run <script> tags in HTML
setInnerHTML(, HTML); // does run <script> tags in HTML
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template