I want to make some refinement to some code from a previous question:
// the new base url
var base = ' https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var links = document.getElementsByTagName('a');
for(var i = 0;i < links.length;i++){
// check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec(links[i].getAttribute('href'));
if(result){
// make a new url using the 'base' and the 'asin' value
links[i].setAttribute('href', base+result[1]);
}
}
Now, instead of it acting on all links, can I get it to only look at links that are from images?
Here is an HTML snippet to show what I mean:
<a href="/shop/product?ie=UTF8&asin=Z00FDLN878&tab=UK_Default" target="_blank"><img width="125" height="125" border="0" src="http://ecx.images-amazon.com/images/I/01W9a7gwosL.jpg" alt="43453"></a>
That's an image link - I do want it to act on that.
My gut instinct is that this isn't actually possible in code - because document.getElementsByTagName('a')
can't see the difference between a text link and an image link.
Use querySelectorAll to pre-select only the right kinds of nodes. EG:
// the new base url
var base = 'https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var linkImgs = document.querySelectorAll ("a > img");
for (var J = linkImgs.length - 1; J >= 0; --J) {
var imgLink = linkImgs[J].parentNode;
//--- Check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec (imgLink.getAttribute ('href') );
if( result) {
// make a new url using the 'base' and the 'asin' value
imgLink.setAttribute ('href', base+result[1]);
}
}