views:

42

answers:

2

Hello. I want to mod a page from a site that prefixes all its links with "http://linkblur.com/?" I tried this:

links = getElementsByTagName('a');
for (l in links) {
    l.href = l.href.replace('http://linkblur.com/?','');
}

But it doesn't work. What am I doing wrong?

tks

Steve

+1  A: 

You for iterator iterates over all the properties of your array, which will not be the individual items, but rather, 0, 1, 2, ..., n, length.

You want to change your iterator, and if you want to prefix the links, you're doing that wrong, too. What you're currently doing will replace linkblur.com... with an empty string, i.e. remove linkblur from existing links.

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].href = 'http://linkblur.com/?' + links[i].href;
}
David Hedlund
The alternative fix would be to use the non-standard [`for each...in`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in), since GreaseMonkey isn't cross-browser anyway.
Matt Ball
@Bears will eat you: GreaseMonkey may not be entirely cross-browser, but it's *more* cross-browser than the `for each` javascript expression. Chrome cannot handle that, but it can run userscripts that do not rely on the `GM_*` API.
David Hedlund
Aha, I see, thanks. But the objective is to remove linkblur prefix. The links are like: http://linkblur.com/?http://foobar.com and I just want the http://foobar.com. So I tried code above with third line replaced by links[i].href = llinks[i].href.replace('http://linkblur.com/?',''); And it still doesn't work.
Steve
@Steve: well, yes, that line should be the only one you have to change, in that case. and your example should work, but you need to make it exact, in your comment, you're using `llinks` instead of `links` in the righthand, and `linkblur.com?`, when you've quoted the url as `linkblur.com/?` (note the slash). apart from that, it should work.
David Hedlund
@David: llinks, duh. It works now. Thanks. BTW, what is the tag for code on this forum? I can't find it in the FAQ and those references to the hrefs didn't display correctly bc it recognized them as links. Tried <code> but it didn't work.
Steve
@Steve: for big blocks of code, indent 4 spaces, for small inline code, and in comments, wrap the text in left angled apostrophes, or whatever they might be called: `. either for block or inline code, you can always highlight the text and press the button with binary on it, in the editor.
David Hedlund
A: 

Try:

var links = document.links;
var link;
for(var i=links.length-1; i >=0; i--){
  link = links[i];
  link.href = link.href.replace("http://linkblur.com/?", '');
}
Erik Vold