javascript - How can you replace a link's target in Greasemonkey? - Stack Overflow

admin2025-04-20  0

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' with 'zyx987' or 'abc123' with 'abc123/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';
}

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.' with 'zyx987.' or 'abc123.' with 'abc123./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';
}
Share Improve this question edited Apr 20, 2010 at 22:56 Yacoby 55.5k16 gold badges117 silver badges121 bronze badges asked Apr 20, 2010 at 21:05 DerekDerek 511 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2
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'; 
} 

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

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

you can also use previous src value:

elem.src += 'index.html';
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745148754a287501.html

最新回复(0)