0

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 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I realised that the code I wrote in the question would not execute, it was an example, and thank you for your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.