Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>var comp = new RegExp(location.host); $('a').each(function(){ if(comp.test($(this).attr('href'))){ // a link that contains the current host $(this).addClass('local'); } else{ // a link that does not contain the current host $(this).addClass('external'); } }); </code></pre> <p>Note: this is just a quick &amp; dirty example. It would match all href="#anchor" links as external too. It might be improved by doing some extra RegExp checking.</p> <hr> <p><strong>Update 2016-11-17</strong></p> <p>This question still got a lot of traffic and I was told by a ton of people that this accepted solution will fail on several occasions. As I stated, this was a very quick and dirty answer to show the principal way how to solve this problem. A more sophisticated solution is to use the properties which are accessible on a <code>&lt;a&gt;</code> (anchor) element. Like @Daved already pointed out in this answer, the key is to compare the <code>hostname</code> with the current <code>window.location.hostname</code>. I would prefer to compare the <code>hostname</code> properties, because they never include the <code>port</code> which is included to the <code>host</code> property if it differs from 80.</p> <p>So here we go:</p> <pre><code>$( 'a' ).each(function() { if( location.hostname === this.hostname || !this.hostname.length ) { $(this).addClass('local'); } else { $(this).addClass('external'); } }); </code></pre> <p>State of the art:</p> <pre><code>Array.from( document.querySelectorAll( 'a' ) ).forEach( a =&gt; { a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' ); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload