Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to check if a link is internal or external

Tags:

jquery

I want to write a script which can determine whether a link is internal or external. This is simple from my perspective, all internal links are relative, so they start with a /. All external links start with an http:// - all good so far. However I can't figure out how to do a ':contains()' on anything other than text - how can a search for a string within an attribute?

Once I can do this I'm happy to add target _blank myself, unless you know a better way to do it

like image 391
chrism Avatar asked Aug 04 '09 13:08

chrism


2 Answers

I'm using WordPress for my CMS, and so most (if not all) of my internal links start with "http". I found a pretty interesting solution here: http://www.focal55.com/blog/jquery-tutorial-add-class-all-outbound-links-your-site

In case that site is down, it basically boils down to this selector (I modified it a bit):

$( 'a[href^="//"],a[href^="http"]' )
    .not( '[href*="' + window.location.hostname + '"]' )
;

Note that this selector will not be the fastest according to the jQuery docs.

like image 177
Dominic P Avatar answered Sep 22 '22 07:09

Dominic P


You could use the attribute^=value syntax to find hrefs that start with http or /:

$("a[href^='http']") // external
 
$("a[href^='/']") // internal

Here's a better solution: You can add $('a:external') and $('a:internal') selectors to jQuery with the plugin code below. Any URL that begins http://, https://, or whatever:// or // is considered external. All other URLs are considered internal.

    $.expr[':'].external = function (a) {
        var PATTERN_FOR_EXTERNAL_URLS = /^(\w+:)?\/\//;
        var href = $(a).attr('href');
        return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
    };

    $.expr[':'].internal = function (a) {
        return $(a).attr('href') !== undefined && !$.expr[':'].external(a);
    };
like image 37
Patrick McElhaney Avatar answered Sep 18 '22 07:09

Patrick McElhaney