Skip to content Skip to sidebar Skip to footer

Target _blank In All Link

I've just made an html page with target _self But now I have too many links and I want to change all link targets to _blank and it's hard for me to do. Is there is any javascript w

Solution 1:

Put this in your <head>:

<basetarget="_blank">

It will make all URLs on a page open in a new page, unlesstarget is specified.

This is a HTML5-only feature, I learned it from Google's io-2012-slides slide package.

Solution 2:

To answer your question, jQuery makes this easy:

<scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><script>
    $(function() {
        $('a[href]').attr('target', '_blank');
    });
</script>

This will not modify any <a> tags without an href attribute.

Solution 3:

It's pretty simple in plain JS too:

var links = document.getElementsByTagName('a');
for (var i=0, len=links.length; i < len; i++) {
  links[i].target = '_blank';
}

(Put this script right before your closing </body> tag or in any case after all the <a> tags on your page.)

Solution 4:

If you are unable to do a simple find and replace using your HTML editor, you can do something like this using jQuery:

$('a').click(function() {
  $(this).attr('target', '_blank');
});

This will automatically do a target="_blank" for every a that is clicked and open in a new window or new tab(you have no control over this, it depends on user's browser settings).

FIDDLE

Hope this helps!!

Solution 5:

I've had to deal with this lots of times. Just for the record:

I think there's no need to make javascript perform this task, but here's another approach, instead you can use the find/replace function of your editor and do something like this (provided your links are in that format):

  • Open your editor and look for <a href:

    Find <a href

  • On the replace field type <atarget="_blank"href.

    Replace

  • Replace.

    Text replaced

Or you can append that to the end of the tag by looking for .com"> and replacing it for .com" target="_blank">. You can do this on all editors that have the find/replace feature. It's just a matter of finding patterns and how to replace them.

Post a Comment for "Target _blank In All Link"