The thing is, the code which you have in the question does work for dynamically inserted content.
The following snippet has one <div class="select-link">
which is part of the HTML and inserts two <div class="select-link">
elements via JavaScript.
jQuery is used to add two separate click
handlers. The first handler is added prior to any of the dynamic content being added to the DOM. The second handler is added after the second <div class="select-link">
is added, but before the third one is inserted. Both handlers are called for all three <div class="select-link">
. This demonstrates that the code you have provided in the question does work for dynamically inserted content. That means something else is going on.
$("#links").on("click", ".select-link"
,logEvent.bind(null,'#links on .select-link','jQuery'));
function logEvent(text,type,e){
var curTarget = (e.currentTarget.id)?e.currentTarget.id:e.currentTarget.nodeName;
var target = (e.target.id)?e.target.id:e.target.nodeName;
console.log(text + ' ::' + type + ' ::curTarget=' + curTarget
+ ' ::target=' + target);
}
function appendLink(id,text) {
document.querySelector('#links').insertAdjacentHTML('beforeend'
,'<div class="select-link" id="' + id + '" style="color:blue;">'
+ text + '</div>');
}
appendLink('sel-pre-ready','Selected Link 2 (added prior to document ready)');
$(document).ready(function(){
$("#links").on("click", ".select-link"
,logEvent.bind(null,'#links on .select-link','jQuery at doc ready'));
appendLink('sel-post-ready','Selected Link 3 (added after document ready)');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Not Link</div>
<div id="links">Links
<div id="not-sel">Not Selected Link</div>
<div class="select-link" id="sel-html" style="color:blue;">Selected Link 1 (HTML)</div>
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
Without more information, spending a lot of time speculating on what might be causing the problem is just wasting time.
One possibility of what is happening is that another event handler is being fired for these events and stopping propagation. One way to (mostly) check for that is to add an event handler to the window
on the capture phase (i.e. not using jQuery). You could do so with the following:
//The following will catch the event prior to almost all possible
// interference by other event handlers.
window.addEventListener('click',function(e){
if(!$(e.target).is("#links .select-link")){
return; //Not one of the elements we are interested in
}//else
//e.stopPropagation();
logEvent('on window','Capture',e);
},true);