how to give target="_blank" to all a tags in html

Viewed 877

i have an html page with alot of links using a tag. i want to open all links in different tabs, instead of setting target="_blank" in all a tags, is there anyway to do it like below in css:

a{target="_blank";}

can anyone please tell, thanks in advance.

3 Answers

Specify a default target for all hyperlinks and forms on a page:

<head>
  <base target="_blank">
</head>

source

you can also add a small script

<script>
document.querySelectorAll('a')
    .forEach(function(elem) {
        elem.setAttribute('target', '_blank');
    })
</script>

If all code is in a single HTML file it would be easiest to run CTRL/CMD+F and add target="_blank"to them. This would be very easy to so in Sublime Text for example.

This could also be easily accomplished with PHP.

Usually, CSS is used to style the HTML markup; therefore I see no real value in adding the target with CSS.

I suggest you think about if you actually want to use target="_blank" on all links as this is generally considered bad practice. See https://www.searchenginejournal.com/when-not-to-use-target_blank-link-attribute/19924/

Also, always use rel="noopener" or rel="noreferrer" to your target="_blank" as omitting these is a security risk! See https://web.dev/external-anchors-use-rel-noopener/

Related