Home > Back-end >  Button doesn't work when added through innerHTML
Button doesn't work when added through innerHTML

Time:11-06

I have a series of buttons that are created in JS to perform a function onclick.

If I write the button on the page itself, it works fine.

But when they're created within JS and written to the document with .innerHTML, they don't function at all.

Is there something about buttons that they won't work when created this way, after the page is loaded? Will I need to add the event listener manually?

As a note, I'm not running this on a server, so everything has to run client-side.

<button  onclick="alert('Button Clicked!')">Text</button>

The HTML is identical. I ran the function, then literally copied the element from the page source and pasted it into the body directly to test it and it works fine there.

CodePudding user response:

It should work as expected; check out the snippet below

document.body.innerHTML =`<button  onclick="alert('Button Clicked!')">Text</button>`

CodePudding user response:

document.body.innerHTML =`<button  onclick="alert('Button Clicked!')">Text</button>`

  • Related