views:

113

answers:

3

I'm trying to write a script in Greasemonkey that will replace a link's target with something else, but with my limited Javascript knowledge I don't really know how to do this.

Basically I'm trying to find all links containing a certain string of characters (ex: //a[contains(@href, 'xx')] ), and either replace them with another link, or append something to them (replacing 'abc123.com' with 'zyx987.com' or 'abc123.com' with 'abc123.com/folder').

If you could point me on the right path I'd greatly appreciate it.

edit: This is working code in case someone has the same question in the future:

var links,thisLink;
links = document.evaluate("//a[contains(@href, 'roarrr')]",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);
for (var i=0;i<links.snapshotLength;i++) {
    var thisLink = links.snapshotItem(i);
    thisLink.href += 'test.html';
}
+1  A: 

You get desired a element(s), and set their src like this:

elem.src = 'http://example.com';

you can also use previous src value:

elem.src += 'index.html';
maid450
Thanks man. This is what I have so far, but it's not working. Could you please take a look?<pre>var links,thisLink;links = document.evaluate("//a[contains(@href, 'roarrr')]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);for (var i=0;i<links.snapshotLength;i++) { var thisLink = links.snapshotItem(i); var src = thisLink.src; thisLink.src += 'test.html';}</pre>
Derek
Should be `href`...
Matthew Flaschen
Heh, that made it work. Thanks!
Derek
d'oh! a's src... to sleep well is also important in solving problems xD
maid450
A: 

Your best bet is to review an existing script that does link rewriting. Look at the script, find others like it, and adapt.

Alex B
+1  A: 
var links = document.evaluate("//a[contains(@href, 'roarrr')]", document, null, 
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); 
for (var i=0; i < links.snapshotLength; i++) 
{ 
  var thisLink = links.snapshotItem(i); 
  thisLink.href += 'test.html'; 
} 
Matthew Flaschen
Thanks mate, I appreciate it!
Derek