Hyperlink with hashtag do not open in new tab

i am using this code to open all the URLs in new tab. but i want the url with # do not open in new tab. for example:

jQuery("a").attr("target", "_blank");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<a href="#">content</a>
<a href="#contact">Contact</a>

Thanks

Answers 1

  • You can check the href attribute value before appending _blank.

    jQuery("a").attr("target", function() {
      if ($(this).attr('href') != '#') {
        $(this).attr('target', '_blank');
      }
    });
    

    In the above code, we check for the href value, if it's # then ignore it, else append _blank value to the elements target.

    Demo


    If you are looking to ignore all a tags where href starts from #, you can do something like

    jQuery("a").attr("target", function() {
      if ($(this).attr('href')[0] != '#') { //checks for the first char, if #, ignore
        return '_blank';
      }
    });
    

    Demo


Related Articles