Home > Web Front-end > JS Tutorial > How Can I Ensure Scripts Execute When Using `innerHTML` in JavaScript?

How Can I Ensure Scripts Execute When Using `innerHTML` in JavaScript?

Linda Hamilton
Release: 2024-12-11 10:55:10
Original
867 people have browsed it

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

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
Copy after login

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!

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