Skip to content
Advertisement

Add onclick event to newly added element in JavaScript

I have been trying to add onclick event to new elements I added with JavaScript.

The problem is when I check document.body.innerHTML I can actually see the onclick=alert(‘blah’) is added to the new element.

But when I click that element I don’t see the alert box is working. In fact anything related to JavaScript is not working..

here is what I use to add new element:

JavaScript

Here is how I call this function:

JavaScript

Now the image draws perfectly inside the browser. But when I click the image I don’t get that alert.

Advertisement

Answer

.onclick should be set to a function instead of a string. Try

JavaScript

instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement