Get onclick="myFunction()" in my button element?

I created a button with createElement.

let myButton = document.createElement("button");
myButton.innerText = "Click";

Now I would insert a function with onclick within the button with javascript.

Like this:

<button onclick="myFunction()">Click</button>

Not sure I know what you are asking but if you create the button in the JS you can’t add the handler in the HTML.

You can add it using addEventListener to the button element you created. You would also have to add the button element to the DOM after it was created and the listener is attached.

let myButton = document.createElement("button");
myButton.innerText = "Click";

myButton.addEventListener('click', () => {
  console.log('button was clicked');
})

document.querySelector('body').appendChild(myButton);
1 Like