Home > database >  Replacing the script tag type and applying it
Replacing the script tag type and applying it

Time:12-13

Is there any way to replace the script type with javascript only and execute it

this is an example script

<script id="myscript" src='myscript.js' type='text/template'></script>

i want to replace type with text/javascript i tried this code to replace it and it does replace the type but the script is not applied to the site.

<script>document.querySelector("#myscript").setAttribute("type","text/javascript");<script>

CodePudding user response:

Make a new script instead, one with the proper type.

const existing = document.querySelector("#myscript");
const newScript = existing.cloneNode();
newScript.type = 'text/javascript';
existing.replaceWith(newScript);

Or just take the src of the existing one.

const existingSrc = document.querySelector("#myscript").src;
document.body.appendChild(document.createElement('script')).src = existingSrc;
  • Related