3

I need to check every script tag's src value and if there is a match, I would like to change that script tags src attribute... Something like this:

var scripts = document.getElementsByTagName("script")[0].src

for (i=0;i<scripts.length;i++){
  if(scripts[i] == "something.js"){
    document.getElementsByTagName("script")[i].src = "this.js"
  }
  else {}
}} 
3
  • That isn't a question, but your first problem here is this code var scripts = document.getElementsByTagName("script")[0].src is getting the src of the first script tag and setting to the variable scripts so it isn't an array and you cannot loop throught it. Commented Nov 4, 2010 at 17:37
  • The problem here is that, by the time you're able to access all of the 'script' tags on the page, they've all been executed. Commented Nov 4, 2010 at 17:38
  • 1
    A couple of comments, in parallel to Álvaro's correct answer: 1) Look at your inner if block - see how you're getting the same script element you just looked up for the comparison? This should hopefully have prompted you to consider Álvaro's version, to just look through the scripts and modify the src(s) that matched (asides from the fact that you can't use .src on a nodelist!). 2) An empty else block is not required and can be omitted. Commented Nov 4, 2010 at 17:40

1 Answer 1

8
var scripts = document.getElementsByTagName("script");

for (i=0;i<scripts.length;i++){
  if(scripts[i].src == "something.js"){
    scripts[i].src = "this.js";
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much... using chrome devtools, it shows the src has been changed, but like Ryan Kinal pointed out, the previous script has already been executed... any workaround?
As far as I know, scripts are executed in the order they appear. That means that your own code must go first to be able to alter the previous scripts and it must go last to be able to find them. It's not trivial at all. We should know the exact details. Feel free to post a new question about it.
You cannot change a src value from html until they is loaded. The same thing that tell you "i can put the remove function before the others" is telling you too "if i don't read the others src below me i cannot change it before they're loaded".

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.