How to Open All Links in New Tabs with JavaScript

Opening links in new tabs instead of the same tab can improve the user experience of your website. It allows users to easily click on links without losing their place on the current page. In this post, I’ll show you how to use JavaScript to open all links in new tabs.

A close-up illustration of a right hand with the index finger pointing directly at a computer screen. The computer screen displays a web page with multiple hyperlinks. The text on the button says "Open all links in new tabs".

Why Open Links in New Tabs

Here are some of the benefits of opening links in new tabs:

  • Users don’t lose their place on your website. If they click a link that opens in the same tab, the current page will unload and they’ll have to hit the back button to return.
  • It’s easier for users to compare information between pages by switching between tabs.
  • Your pages could get more pageviews since users can easily click links without fear of losing the current page.

The target=”_blank” Attribute

The easiest way to open a link in a new tab is by adding the `target=”_blank”` attribute to anchor tags:

<a href="about.html" target="_blank">About</a>

However, this requires manually adding the attribute to every single link. We want to save time by automatically opening all links this way.

Automating with JavaScript

To assign the `target=”_blank”` attribute to all links, we can use the following JavaScript:

// Select all anchor tag links
const links = document.querySelectorAll('a'); 

// Loop through each link
links.forEach(link => {

  // Add target="_blank" attribute
  link.setAttribute('target', '_blank');
  
});

This code grabs all anchor tags, loops through them with `.forEach()`, and sets the `target` attribute to `_blank` on each one.

Now all links will open in a new tab!

links.forEach(link => {

  // Exclude navigation links
  if (!link.classList.contains('nav-link')) { 

    link.setAttribute('target', '_blank');
  
  }

});

This checks if a link has a `nav-link` class first before setting the attribute.

So that’s an easy approach to open all external links in new tabs using plain JavaScript! Let me know if you have any other questions.

Share this content:

Post Comment