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
x
15
15
1
function add_img() {
2
var elemm = document.createElement('rvml:image');
3
elemm.src = 'blah.png';
4
elemm.className = 'rvml';
5
elemm.onclick = "alert('blah')";
6
document.body.appendChild(elemm);
7
elemm.id = "gogo";
8
elemm.style.position='absolute';
9
elemm.style.width=55;
10
elemm.style.height=55;
11
elemm.style.top=200;
12
elemm.style.left=300;
13
elemm.style.rotation=200;
14
}
15
Here is how I call this function:
JavaScript
1
2
1
<button onclick=add_img()>add image</button>
2
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
1
2
1
elemm.onclick = function() { alert('blah'); };
2
instead.