How to Open All a Links on a Page in New Windows with JavaScript?

Sometimes, we want to open all a links on a page in new windows with JavaScript.

In this article, we’ll look at how to open all a links on a page in new windows with JavaScript.

Open All a Links on a Page in New Windows with JavaScript

To open all a links on a page in new windows with JavaScript, we can set the target attribute of all the a elements to _blank.

For instance, if we have:

<a href='https://google.com'>google</a>
<a href='https://yahoo.com'>yahoo</a>
<a href='https://bing.com'>bing</a>

Then we write:

const links = document.querySelectorAll('a')
for (const l of links) {
  l.target = '_blank'
}

We select all the a elements with document.querySelectorAll and assign the select the node list of elements to links.

Then we use the for-of loop to loop through all the links and set the target attribute to _blank by setting the target property to '_blank'.

Now the links should all open on a new tab.

Conclusion

To open all a links on a page in new windows with JavaScript, we can set the target attribute of all the a elements to _blank.