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:
is()returnstrueif the selected element matches the selector in the function andfalseif it does not. So, if the current link’shrefattribute containsgoogle.ca, it’ll change itstargetattribute to_self. Otherwise, it’ll set it to_blank.And, in fact, for more efficiency, you should cache
$(this):