Q:

How to make button open a link in new tab in JavaScript?

I want to create a <button> that when clicked will open a URL in a new tab.
This is easy to achieve in pure HTML, but the catch is that the <button> is dynamically generated, thus this has to be done in JavaScript.
This is the code I used to create a <button> so far using JavaScript and HTML DOM:
<body>
  <div id = 'only_div'>
  </div>
  <script>
    var btn=document.createElement("button");
    btn.innerText = "Click me";
    document.getElementById("only_div").appendChild(btn);
  </script>
</body>

In this existing code, I just want to add that when clicked, a URL (for example http://www.stackoverflow.com) will open in a new tab.

A:

You can add a click event listener to the button with addEventListener() and  then when it's trigger use window.location.replace() to redirect.
<body>
    <div id = 'only_div'>
    </div>

    <script>
      var btn=document.createElement("button");
      btn.innerText = "Click me";
      btn.addEventListener("click", ()=>{
         window.location.replace(URL);
      });
      document.getElementById("only_div").appendChild(btn);
    </script>

</body>

for a new tab use:
window.open(URL, '_blank');

Docs:

addEventListener
replace()
open()

A:

You could do something like the following, which will open the tab in a new tab and go to this tab:
function openInNewTab(url) {
  const win = window.open(url, '_blank');
  win.focus();
}

const btn=document.createElement("button");
btn.innerText = "Click me";
btn.addEventListener('click', function () {
    openInNewTab('http://www.test.com')
});
document.getElementById("only_div").appendChild(btn);

See js fiddle here.

