Here is my problem. I have a function where I dynamically create <input /> elements and I am trying to register a handler on mouseclick with parameter. I call this function few times and only the last input has the handler assigned. Here is the simplified code:
function create() {
var div = document.getElementById("myId");
var vRemove = document.createElement("span");
vRemove.innerHTML = "remove";
var foo = 4;
vRemove.onclick = function(){ remove(foo); }
div.innerHTML += " ";
div.appendChild(vRemove);
}
function remove(id) {
alert(id);
}
create();
create();
create();
and in HTML I have only one div:
<div id='myId'></div>
When I click the 3rd element an alert pops up but those other two do nothing at all. What am I doing wrong?
This line of code that you’ve now clarified your answer with:
wipes out all previous programmatic event handlers assigned to children of
myIdso the only one that would be left is the last one you add – thus why thus why only the last input handler works. Assigning to innerHTML reparses the HTML from scratch and re-initializes all those objects. Any programmatic changes you have made to them (in your case, assign a click handler) may be lost.The downside of using innerHTML to modify your page is that is may wreck programmatically assigned event handlers and other programmatic changes. I try to only use it when building new HTML or when setting the contents of one element (e.g. what text displays).