0

I am getting one document from api response which contains html like this

I am inserting this document as innerHTML inside one page It is rendering properly but script is not executing.Please help me with this.How to set html so that script inside that also execute.

I tried to use set page as innerHTML

<html>
    <head></head>
    <body>
        <div>
            <div>This is my Name</div>
            <div>This is something else</div>
        </div>
        <script src="demo_script_src.js"></script>
    </body>
</html>

sneha
  • 435
  • 4
  • 9

1 Answers1

0

Replace response with your html code, and targetElement

var parser = new DOMParser();
var parsedHtml = parser.parseFromString(response, 'text/html');

var scriptTags = parsedHtml.querySelectorAll('script');

for (var i = 0; i < scriptTags.length; i++) {    
    var newScriptTag = document.createElement('script');
    newScriptTag.textContent = scriptTag.textContent;
    
    document.head.appendChild(newScriptTag);
}

var targetElement=...;
targetElement.append(...parsedHtml.documentElement.childNodes);
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Iliasse
  • 94
  • 6