1

I have this tool that uses both hard and relative links for local pages. (I didn't build it) I now need to classify external links. Tried with this but it gets stuck at the 'else if' level. What am I doing wrong? Without the 'else if' it mistakenly marks some local links as external, but with it, nothing happens.

jQuery(document).ready(function() {
    var comp = new RegExp(location.host);
    jQuery('a').each(function(){
        if(comp.test(jQuery(this).attr('href'))) {
            jQuery(this).addClass('local');
        }
        else if(jQuery(this)('a[href$="ABC"]')) {
            jQuery(this).addClass('local2');
        }
        else {
        jQuery(this).addClass('external');
    }    
});
ankur140290
  • 640
  • 9
  • 25
Dave Able
  • 21
  • 2

1 Answers1

3

Your existing code is invalid and should show a console error as the following is not a valid expression:

jQuery(this)('a[href$="ABC"]')

As you generally need to identify external links only, and any internal links are treated the same (absolute or relative) I have this jQuery selector that will match all the possible external links (including email & file links etc):

'a[href*="://"]:not(a[href^="' + window.location.protocol + '//' + window.location.hostname + '"]),a[href^="mailto:"]'

JSFiddle: http://jsfiddle.net/TrueBlueAussie/qxn8L86a/10/

Simplified version (if your site has no absolute local links):

$('a[href*="://"],a[href^="mailto:"]').addClass("external");

JSFiddle: http://jsfiddle.net/TrueBlueAussie/qxn8L86a/8/

To add a class to the local links you can just exclude the external ones:

e.g.

$('a').not($('a[href*="://"],a[href^="mailto:"]').addClass("external")).addClass("local");

JSFiddle: http://jsfiddle.net/TrueBlueAussie/qxn8L86a/9/

Reference (my question) here: RegEx expression or jQuery selector to NOT match "external" links in href

Community
  • 1
  • 1
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202