Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if links are external with jQuery / javascript?

How do I test to see if links are external or internal? Please note:

  1. I cannot hard code the local domain.
  2. I cannot test for "http". I could just as easily be linking to my own site with an http absolute link.
  3. I want to use jQuery / javascript, not css.

I suspect the answer lies somewhere in location.href, but the solution evades me.

Thanks!

like image 278
Matrym Avatar asked May 26 '10 07:05

Matrym


1 Answers

I know this post is old but it still shows at the top of results so I wanted to offer another approach. I see all the regex checks on an anchor element, but why not just use window.location.host and check against the element's host property?

function link_is_external(link_element) {     return (link_element.host !== window.location.host); } 

With jQuery:

$('a').each(function() {     if (link_is_external(this)) {         // External     } }); 

and with plain javascript:

var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) {     if (link_is_external(links[i])) {         // External     } } 
like image 139
Daved Avatar answered Oct 04 '22 20:10

Daved