Using HTML DOM to change contents of Script Tag

When we use html dom,we normally run code such as :

document.getElementById('id').innerHTML = 'new text'
to change the contents of a tag such as <div>

However I tried this with the <script> tag and it doesn’t seem to be working. What should I try?

document.getElementsByTagName('script')[0].innerHTML = "document.write('ok')"

1 thought on “Using HTML DOM to change contents of Script Tag”

  1. Let’s say you have a collection of scripts:

    var scripts = document.getElementsByTagName('script');

    Executing scripts[0].innerHTML = "document.write('ok')" will effectively change the script’s content, but the script’s new content will not be executed.

    The solution is straightforward:

    1. Delete the script you want to update.
    2. Create a new script and add it to the page’s body. It will be executed.

    With your to-be-updated script in the body this equals to:

    document.body.removeChild(scripts[0]);
    var newScript = document.createElement('script');
    newScript.innerHTML = 'document.write("ok")';
    document.body.appendChild(newScript);
    
    Reply

Leave a Comment