Search code examples
javascriptjqueryurlhref

How to apply javascript function to href with specific domains


I need to add redirect to other links in my website, I use

window.onload = function() {
   var anchors = document.getElementsByTagName("a");

   for (var i = 0; i < anchors.length; i++) {
       anchors[i].href = "http://shorter.com/?redirect=" + anchors[i].href
  }
}

This will add to all links, but I need to specify only domains to redirect them only like:

var domains = ['depositfiles.com', 'rapidshare.com']; 

Edit

for example my page has many links (file.com, depositfiles.com, inda.com). I need only href with domains in the "domain" variable redirected using my redirector while other is kept the same (direct).

Like for depostitfiles.com http://shorter.com/?redirect=http://depositfiles.com/

for inda.com http://inda.com


Solution

  • Just use hostname matching:

    var domains = ["google.com", "stackoverflow.com"];
    
    window.onload = function() {
       var anchors = document.getElementsByTagName("a");
    
       for (var i = 0; i < anchors.length; i++) {
          for(var j = 0; j < domains.length; j++){
            if(anchors[i].hostname === domains[j]){ //domain present
              anchors[i].href = "http://shorter.com/?redirect=" + anchors[i].href
              break;
            }
          }
      }
    }

    Good point @jonathan-gray - edited