Open a link in a new tab using the anchor tag in JavaScript

Open a link in a new tab using the anchor tag in JavaScript

Posted by Ervin Adams on July 24, 2022

Open a link in a new tab using the anchor tag in JavaScript

Open a link in a new tab using the anchor tag in JavaScript

Posted by Ervin Adams on July 24, 2022

Here is how you can open a link in a new tab using anchor tag:

Set attributes to anchor tag:

<a href="https://google.com" target="_blank">Click here</a>

The href attribute specifies the url and the target attribute specifies where to open the link. 

HTML onclick attribute:

<a href="#" onclick="window.open('https://google.com', '_blank')">Click here</a>

The onclick attribute fires on click of the anchor tag element.

JavaScript addEventListener:

HTML

<a href="#" id="open-link">Click here</a>

JS

let openLink = document.getElementById('open-link');

openLink.addEventListener('click', () => {
  window.open('https://google.com', '_blank');
});

Select the anchor tag element using document.getElementById. Once the a tag is clicked addEventListener will be called.