I'm doing a javascript experiment that when clicking on a certain element with a certain class we will add a new element with the same class, whenever a new element should be clicked.
var my_divs = document.getElementsByClassName('my-div');
for (var i = 0; i < my_divs.length; i++) {
my_divs[i].addEventListener('click', function() {
var next_id = my_divs.length + 1;
document.body.innerHTML += '<div id="div' +next_id+ '" class="my-div"></div>';
//console.log(next_id);
});
}
.my-div {
width:20px;
height:20px;
}
.my-div:nth-child(odd) {
background-color:red;
}
.my-div:nth-child(even) {
background-color:blue;
}
<div id="div1" class="my-div">
</div>
As you can see, it works, but only once. I even understand that clicking the one that appears dynamically does nothing because the event did not get associated with the new div. But anyway, why does the click on the first only work once? And how would you do to get what I want? Whenever I click on any ( .my_div
), dynamically generated or not another appears?