DEV Community


Discussion on: Dynamically Made Button

link2twenty profile image
Andrew Bone

Nice first post 😀

Generally, I would probably use createElement to push a new node, rather than appending HTML to the DOM directly. There are several ways to do this, I'm a fan of classes so I'd probably make a class that creates the node and then append that. Like so:

class BasicButton {
  constructor(id, text) {
    this.node = document.createElement('button');
    this.node.setAttribute("id", id);

let button = new BasicButton("form_submit", "Submit");
button.node.addEventListener("click", someFunction);

This has the added bonus of being able to reference button.node to make changes to the element even though it's in the DOM.

Here's an example of it in practice, though I've added a class and some CSS to make it a little fancier 😉