JavaScript Code


How to set all links to open in new tab using JavaScript?


Tutorials using JS

Set all links to open in new tab

make link to open in new tab when user clicks on the respective link, the same for all the links in the document, using JavaScript

Solution

to make a link open in new tab, its target property must be set with the value _blank

<a href="/a-link/" target="_blank">A link</a>

Program

in the following HTML code, we have two link elements. when user clicks on the button, we make the links set to open in new tab by setting their target property

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Make links open in new tab</h2>
<button id="myBtn">Click me</button><br>
<a href="/line-one/">Link 1</a><br>
<a href="/link-two/">Link 2</a>

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    const links = document.getElementsByTagName("a");
    for ( let i = 0; i < links.length; i++ ) {
        //set link to open in new tab
        links[i].setAttribute("target", "_blank");
    }
});
</script>

</body>
</html>

Copyright @2022