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?
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');
}
var homeURL = 'google.ca';
$('a').each(function() {
$(this).attr('target', (this.href.match( homeURL )) ? '_self' :'_blank');
});
You can also achieve this with:
$(document).ready(function() {
$("a[href^='http']").attr('target','_blank');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With