0

I dynamically create a link to a. 'mywebsite' is a variable. Everything works but the mywebsite page replaces that of the code. I want to open mywebsite in another page. May I have a help to solve the problem ?

var mylink = document.createElement("a");
        var textForButton = document.createTextNode("More details");
        mylink.appendChild(textForButton);    
        mylink.setAttribute("href", mywebsite);
        document.body.appendChild(mylink);

2 Answers 2

1

You should set the linke target as this:

mylink.setAttribute("target", '_blank');

Your code my be something like this

    <script>
        window.onload = function () {
            let mywebsite = "http://www.google.com";
            var mylink = document.createElement("a");
            var textForButton = document.createTextNode("More details");
            mylink.appendChild(textForButton);
            mylink.setAttribute("href", mywebsite);

            mylink.setAttribute("target", '_blank');

            document.body.appendChild(mylink);
        };
    </script>

Sign up to request clarification or add additional context in comments.

Comments

0

You can set target=_blank attribute to do this.

mylink.setAttribute("target", "_blank");

So that once you click on the link that you have generated it opens in new tab.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.