Search code examples
javascriptclick

click event on innerHTML generated div


I have a 'div' element generated in javascript with 'innerHTML' property.

(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';

Anyway onclick event is not working.

document.getElementById('a').onclick = function() {
    //do something
}

What is the problem? How do I resolve it (pure javascript, no libraries)?


Solution

  • You could delegate the event listening to the parent to which you are innerHTML-ing the div , in yout code indicated by (...). This would handle the events fired in the (...) and you can perform actions conditioned to event.target.id === 'a'

    (...).onclick = function(event) {
        if (event.target.id === 'a') {
        //Do your stuff
        }
    }
    

    This way you not need to worry about if, when you attach the listener, you have already created the div dinamically or not. Also, to register the event handler, I suggest proper event handle registering (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)