JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div class="card">
<div id="cards">
<div class="card"><div class="inner-card"></div></div>
<div class="card"><div class="inner-card"></div></div>
<div class="card"><div class="inner-card"></div></div>
<!-- without the base.contains(closest) check in the event listener,
clicking this would trigger the event due to the
outter .card element even though it should not -->
<div class="rogue-child"></div>
</div>
</div>
<button onclick="addCard()">
Add Card
</button>
<script>
function addCard() {
var base = document.getElementById('cards');
var el = document.createElement('div');
el.classList.add('card');
var inner = document.createElement('div');
inner.classList.add('inner-card');
el.appendChild(inner);
base.appendChild(el);
}
</script>
</body>
CSS
#cards .card {
background-color: red;
display: inline-block;
position: relative;
width: 50px;
height: 50px;
margin: 10px;
}
.rogue-child {
background-color: gray;
display: inline-block;
width: 50px;
height: 50px;
margin: 10px;
}
.inner-card {
background-color: green;
position: absolute;
top:10px;
left:10px;
right:10px;
bottom:10px;
}
.blue, #cards .blue {
background-color: blue;
}
.blue .inner-card {
background-color: orange;
}
JavaScript
var base = document.querySelector('#cards');
var selector = '.card';
base.addEventListener('click', function(event) {
let closest = event.target.closest(selector);
if (closest && base.contains(closest)) {
closest.classList.add('blue');
}
});