The joys of XPATH

I did up a new greasemonkey script for something that has been annoying me for a while. It is a site I view where a number of links to items are shown. But you have to click through numerous links to find the correct images.
This time I tried out XPATH and I have to say I am very impressed with it. Makes life so much easier.

Here is the breakdown of the code. First using XPATH I tell it to return all links which point to an image file.

var links = document.evaluate(
‘//a[contains(@href,”gif”) or contains(@href,”jpg”) or contains(@href,”png”)]’,

Next create the loop to examine all the Anchor links (a).

for (var i = 0; i < links.snapshotLength; i++) {
var a = links.snapshotItem(i);

Now that I have the link I create a new IMG element (img), set the attributes of it.

     var img = document.createElement(‘img’);
img.setAttribute(‘src’, a.getAttribute(‘href’));
img.setAttribute(‘style’,’width: 50%; height: 50%’);

Lastly I replace the text contained within the anchor link with the IMG element (and close the loop).

   a.replaceChild(img, a.firstChild);

And that is the lot! So simple and clean.