Skip to content
Related Articles

Related Articles

How to simulate target=“_blank” in JavaScript ?
  • Difficulty Level : Basic
  • Last Updated : 17 Feb, 2020

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :