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 {}
}} 
David
  • 13,619
  • 15
  • 45
  • 51
  • 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. – 3urdoch Nov 04 '10 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. – Ryan Kinal Nov 04 '10 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. – Andrzej Doyle Nov 04 '10 at 17:40

1 Answers1

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

for (i=0;i<scripts.length;i++){
  if(scripts[i].src == "something.js"){
    scripts[i].src = "this.js";
  }
}
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • 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? – David Nov 04 '10 at 17:43
  • 1
    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. – Álvaro González Nov 04 '10 at 17:51
  • 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". – m3nda Nov 14 '13 at 04:39