How to use jQuery not selector to select relative urls?

I am working on a little jQuery script to add Google Analytics pageTracker onclick data to all relative urls in my forum, allowing me to track clicks on external sites.

I don't want to add onclick to internal links to forum.sitename or sitename, and I don't want to add them to any hrefs marked with # or starting with /. My script below works nicely, but for one minor problem!

All forum urls are relative and do not start with /. I can't seem to change this, so I need to change the jQuery below to prevent onclick from being added to links as it currently does.

What I want to do is write a .not () function like .not ("[href! ^ = Http") to prevent jQuery from adding onclick to any hrefs that don't start with http. However .not () doesn't seem to support this.

I am new to jQuery and cannot figure it out. Any pointers would be widely appreciated.

$(document).ready(function(){
     // Get URL from a href
     var URL = $("a").attr('href');

 // Add pageTracker data for GA tracking
 $("a")
 .not("[href^=#]")
 .not("[href^=http://forum.sitename]")
 .not("[href^=http://www.sitename]")
 .attr("onclick","pageTracker._trackEvent('Outgoing_Links', 'Forum', " + URL + ");")
 ;

});

      

Thanks!

+2


a source to share


2 answers


You can write a non selector like this to get links that do begin with http

but do not contain "sitename.com":

$('a[href^=http]:not([href*="sitename.com"])')

      

You can play with the example here , this uses a string based :not()

selector
and ^=

starts with the selector
you are already using and *=

contains an eelector element
.



Update based on comments:

$(functon() {
  $('a[href^=http]:not([href*="sitename.com"])').click(function() {
    pageTracker._trackEvent('Outgoing_Links', 'Forum', this.href);
  });
});

      

+4


a source


var regex = RegExp('^(?:f|ht)tps?://(?!' + location.hostname + ')');

$('a').filter(function(){
    // Filter-out internal links
    return regex.test(this.href);
}).click(function(){
    pageTracker._trackEvent('Outgoing_Links', 'Forum', this.href);
})

      



+2


a source







All Articles