Search code examples
javascriptinteraction

Create Buttons with only Javascript


I've been trying to create a basic card game. The idea is that it shows you cards, and you click on a button and it flips the card or changes color or whatever. Im doing this for school, so I'm doing this on a site called codehs.com that has its own javascript editor.

https://codehs.com/share/8xBGa1CKkI4paE35nY9x
(link to the site)

The problem is that as far as i can tell, the only way to actually create a button is with html, and have it interact with javascript through a webpage. This is a problem because I don't know how to do this with javascript alone.

My question is, is there any way to create a button as an object in a Javascript without, without any html?

first time asking, sorry if this isn't the best way of asking Thanks in advance (and those who've answered, i appreciate the help)


Solution

  • I don't know the environment you are talking about -- a link there would really help, but assuming you at least have access to the DOM, it is easy enough to create a button via JavaScript.

    var button = document.createElement("button");
    button.innerHTML = "click me!";
    
    button.addEventListener("click", function() {
      button.innerHTML = "You did it";
    });
    
    document.body.appendChild(button);