Unfundednut
Unfundednut

Reputation: 334

Greasemonkey - Find link and add another link

We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.

var links = document.evaluate("//a[contains(@href, 'NFD')]", document, null, 
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); 
for (var i=0; i < links.snapshotLength; i++) 
{ 
  var thisLink = links.snapshotItem(i); 
  newElement = document.createElement("p");
  newElement = innerHTML = '&nbsp;&nbsp;<a href="' + url + '">Remote</a>';
  thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
  //thisLink.href += 'test.html'; 
} 

Edit:

What I am looking for basically is I have a link <a href="http://blargh.tld/Search-Computer.asp?Computer=NFDM0026">NFDM0026</a> I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.

Upvotes: 1

Views: 1403

Answers (1)

Brock Adams
Brock Adams

Reputation: 93473

Here's how to do what you want (without jQuery; consider adding that wonderful library):

//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");

for (var J = links.length-1;  J >= 0; --J) { 
    var thisLink            = links[J]; 
    var newElement          = document.createElement ("p");
    var newURL              = thisLink.textContent.trim ();
    newURL                  = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
    newElement.innerHTML    = '&nbsp;&nbsp;<a href="' + newURL + '">Remote</a>';

    InsertNodeAfter (newElement, thisLink);
} 

function InsertNodeAfter (newElement, targetElement) {
    var parent  = targetElement.parentNode;
    if (parent.lastChild == targetElement)
        parent.appendChild  (newElement);
    else
        parent.insertBefore (newElement, targetElement.nextSibling);
}

Upvotes: 3

Related Questions