Change the target attribute of a link if its href attribute contains a specific phrase

I am trying to check all the .each() tags with .each() and set a target for home URLs for _self and other destination addresses of other home users in _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'); } }); 

Here is also jsBin here .

For some reason, non-homepage URLs are set to target="_self" . Can someone explain why?

+4
source share
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 item matches the selector in the function and false if it is not. So, if the current link href attribute contains google.ca , it will change its target attribute to _self . Otherwise, it will set the value to _blank .

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

 var $this = $(this); if($this.is("[href*=" + homeURL + "]")){ $this.attr('target','_self'); } else { $this.attr('target','_blank'); } 
+6
source
 var homeURL = 'google.ca'; $('a').each(function() { $(this).attr('target', (this.href.match( homeURL )) ? '_self' :'_blank'); }); 
+7
source

You can also achieve this with:

 $(document).ready(function() { $("a[href^='http']").attr('target','_blank'); }); 
+2
source

Source: https://habr.com/ru/post/1398532/


All Articles