Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change link target attribute if its href attribute contains certain phrase

I am trying to check all anchors' tags using .each() and set home URLs' target to _self and other non-home URLs' target to _blank.

So far, I got this:

$('a').each(function() {
    var homeURL = 'google.ca';    
    if ( $(this+'[href*='+homeURL+']')) {
        $(this).attr('target','_self');
    }else{
        $(this).attr('target','_blank');
    }  
});

This is also on jsBin here.

For some reason, the non-home URLs set to target="_self". Can anyone explain why?

like image 777
FoxKllD Avatar asked Feb 27 '12 04:02

FoxKllD


3 Answers

Try this instead:

if($(this).is("[href*=" + homeURL + "]")){
    $(this).attr('target','_self');
} else {
    $(this).attr('target','_blank');
}

is() returns true if the selected element matches the selector in the function and false if it does not. So, if the current link's href attribute contains google.ca, it'll change its target attribute to _self. Otherwise, it'll set it to _blank.

And, in fact, for more efficiency, you should cache $(this):

var $this = $(this);
if($this.is("[href*=" + homeURL + "]")){
    $this.attr('target','_self');
} else {
    $this.attr('target','_blank');
}
like image 64
Purag Avatar answered Oct 14 '22 14:10

Purag


var homeURL = 'google.ca';
$('a').each(function() {        
    $(this).attr('target', (this.href.match( homeURL )) ? '_self' :'_blank');       
});
like image 7
charlietfl Avatar answered Oct 14 '22 14:10

charlietfl


You can also achieve this with:

$(document).ready(function() {
  $("a[href^='http']").attr('target','_blank');
});
like image 2
fkoessler Avatar answered Oct 14 '22 15:10

fkoessler