Open In App

How to simulate target=“_blank” in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

The HTML target attribute defines where the linked document will open when the user clicked on the link. If target=”_blank” is set with anchor element, then the linked document will open in a new tab otherwise document is open in the same tab. There are two methods to execute this task. One is the normal older and lengthy way, where target=”_blank” attribute is written inside the HTML tag. Another convenient way is to execute through javascript code.

Approach: At first we will create an event on every click function then we set the condition if there is an anchor tag and the target attribute is not mentioned, target attribute as “_blank”.

Syntax:

 document.addEventListener("click", function(e) {
    if (e.target.tagName == "A" &&
            !e.target.hasAttribute("target"))
    {
        e.target.setAttribute("target", "_blank");
    }
}); 

Below example illustrate the target=”_blank” in JavaScript:
Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Simulate target=“_blank” in JavaScript
    </title>
      
    <script>
        document.addEventListener("click", function(e) {
            if (e.target.tagName == "A" &&
                    !e.target.hasAttribute("target"))
            {
                e.target.setAttribute("target", "_blank");
            }
        });
    </script>
</head>
  
<body style="text-align:center">
      
    <a href="https://www.geeksforgeeks.org/">
        GeeksforGeeks<br>
        A computer science portal for geeks
    </a>
</body>
  
</html>


Output:


Last Updated : 17 Feb, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads