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:

function add_img() { 
  var elemm = document.createElement('rvml:image'); 
  elemm.src = 'blah.png';
  elemm.className = 'rvml';
  elemm.onclick = "alert('blah')";
  document.body.appendChild(elemm);
  elemm.id = "gogo";
  elemm.style.position='absolute';
  elemm.style.width=55;
  elemm.style.height=55;
  elemm.style.top=200;
  elemm.style.left=300;
  elemm.style.rotation=200; 
}

Here is how I call this function:

<button onclick=add_img()>add image</button>

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


Solution 1:

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

elemm.onclick = function() { alert('blah'); };

instead.

Solution 2:

You can also set attribute:

elem.setAttribute("onclick","alert('blah');");

Solution 3:

Not sure but try :

elemm.addEventListener('click', function(){ alert('blah');}, false);