tags:

views:

58

answers:

2

I want to write a greasemonkey script/chrome user script that takes any images with a certain syntax and replace a section of the url and puts it back in the dom.

Namely I have a page full of thumbnails, e.g. www.example.com/small/randomstuff and I want to replace the imades with the equivilant www.example.com/large/randomstuff

How would I do this?

+2  A: 

To replace a image source url, you can do something like this:

var imgs = document.getElementsByTagName('img')
imgs[0].src = "http://www.example.com/large/randomstuff"
jbochi
don't forget the `http://` ;)
Jason
@Jason: I fixed it for him.
Asaph
Edited. Thanks! ;)
jbochi
I gave you an upvote as it does the meat of the work, but Itay Moavs answer does everything
Tom J Nowell
+4  A: 

After page was loaded.

var imgs = document.getElementsByTagName('img');
var len =imgs.length;
for(var i=0;i<len;i++){
  imgs[i].src=imgs[i].src.replace("small","large");
}
Itay Moav
actually, this is the more correct answer, as the OP wants all thumbnails replaced
Jason
thankyou mr ^_^
Tom J Nowell
You can use the alternative for syntax, and avoid having to create the `len` variable, by doing `for(var i in imgs)`.
Atli
@Atli Assuming you will use in the future some kind of library (like JQ or Mootools) this will make your code less portable, as those libraries add properties to the Array object.
Itay Moav
@Atli: I've always read that you should avoid the `for( x in y )` loop in JavaScript because it's quite inefficient. Maybe not a big deal here, but... yeah.
Jeff Rupert
You definitely don't want `for...in` here. Quite apart from the prototype-extension issue with libraries, it will give you other non-numeric properties of `NodeList`, like `item`, `namedItem` and `length`. Don't use `for...in` against `Array` or other sequences, it is always the wrong thing. Incidentally you can use `document.images` as an old-school short-cut for the `getElementsByTagName` call.
bobince
Ahh ok. I wasn't aware of those issues. Thanks for correcting me!
Atli