JSFiddle - React, Tailwind, and code Playground

by JeroenSormani

HTML

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
function addnew(id) {
    var item = document.createElement('template')
    item.innerHTML = '<div class="item"><p class="child-elem">Child has text</p></div>'
    document.getElementById(id).appendChild( item.content.firstChild )
}
</script>

<div id="one">
    <h3>One - doesn't work on child click</h3>
    <div class="item"><p class="child-elem">Child has text</p></div>
    <div class="item"><p class="child-elem">Child has text</p></div>
</div>
<a onclick="addnew('one')" href="javascript:void(0);">Add new</a>

<div id="two">
    <h3>Two - doesn't work on newly added elements</h3>
    <div class="item"><p class="child-elem">Child has text</p></div>
    <div class="item"><p class="child-elem">Child has text</p></div>
</div>
<a onclick="addnew('two')" href="javascript:void(0);">Add new</a>


<div id="three">
    <h3>Three - Works with jQuery > looking for JS solution</h3>
    <div class="item"><p class="child-elem">Child has text</p></div>
    <div class="item"><p class="child-elem">Child has text</p></div>
</div>
<a onclick="addnew('three')" href="javascript:void(0);">Add new</a>

CSS

.item { border: 3px solid red; margin-bottom: 10px; }
.child-elem { border: 3px solid blue; }

JavaScript

// This doesn't listen to children in .item
document.getElementById('one').addEventListener('click', function(e) {
    if (e.target.classList.contains('item')) {
        alert('click in One');
    }
});

// Does work on childs, but doesn't work on newly added elements
document.getElementById('two').querySelectorAll('.item').forEach(function(elem) {
    elem.addEventListener('click', function(e) {
        alert('Click in Two')
    })
})

jQuery('#three').on('click', '.item', function() {
	alert('Click in three')
})