0

I am trying to create a button remotely to go to a page. I can create the button, I just don't know how to add a "onclick" inside my button.

I have tried to appendChild() of the button, and that doesn't work. I have also tried to make the button an <a>, that also didn't work.

var btn = document.createElement("button");
var txt = document.createTextNode(name);
var lnk = document.createTextNode("fooPage");
btn.appendChild(txt);
document.body.appendChild(btn);

A button should appear to take the user to a new page (marked by fooPage).

Darrow Hartman
  • 4,142
  • 2
  • 17
  • 36

1 Answers1

0

What you want to do is to put the button inside of an a. You can then set the href attribute of the a tag with .setAttribute(attrName, attrValue).

var btn = document.createElement("button");
var txt = document.createTextNode("button");

// Create an 'a' element.
var lnk = document.createElement("a");

// Set the 'href' attribute of the 'a' element.
lnk.setAttribute("href", "https://example.com");

btn.appendChild(txt);

// Nest the button inside the a tag.
lnk.appendChild(btn);

// Add the a tag to the dom.
document.body.appendChild(lnk);

If instead of redirecting the user, you want to set the onclick attribute (or any other attribute) of a button (or any other element) for a different purpose, you could use .setAttribute on the btn element.

var btn = document.createElement("button");
btn.setAttribute("onclick", "alert('Hello, World!')");
jeffkmeng
  • 851
  • 1
  • 8
  • 30