How Can I Refine This Javascript Code So It Ignores Links From Images
This is a variation of an existing question {Please note - this question is the opposite/inverse of an existing StackOverflow question that is too complex to answer there} From the
Solution 1:
In straight javascript / DOM, test the links as you loop through them:
var base = 'https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var linksNoImg = document.querySelectorAll ("a[href*='asin']");
for (var J = linksNoImg.length - 1; J >= 0; --J) {
var imgLink = linksNoImg[J];
//--- Make sure it's not an image link:if ( ! imgLink.querySelector ('img') ) {
//--- Check each link for the 'asin' valuevar 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]);
}
}
}
jQuery lets you preselect only the correct links:
//--- The new base URLvar base = ' https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var linksNoImg = $("a[href*='asin']:not(:has(img))");
linksNoImg.each ( function () {
// check each link for the 'asin' valuevar 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]);
}
} );
But this requires you to load jQuery in Greasekit -- which is well worth it for any but the simplest scripts.
Solution 2:
if (links[i].querySelector('img')) {
// Link has an <img>! Oh no!
}
To support older browsers, call getElementsByTagName()
instead (and check for an empty array).
Post a Comment for "How Can I Refine This Javascript Code So It Ignores Links From Images"