javascript - Addinf event listeners for Dynamically added elements - HTML/JS -
i trying add event listeners html elements have been dynamically added using javascript. have div in main page
<div id="someid"></div>
and on click of button eventlistener as
document.getelementbyid("someid").innerhtml = "<input type='button' id ='ad' value='add' style='height:30px; width:90px'/>" document.getelementbyid("ad").onclick = notherfunc;
and function like
function notherfunc(){ alert("working") }
but isn't working. there way bind button function?
you need use technique called "event delegation". essentially, need bind click handler element exists , see if element clicked element expecting.
document.getelementbyid("someid").addeventlistener("click", function (e) { if (e.target.id === "ad") { notherfunc(); } });
Comments
Post a Comment