1
I am 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 clicking should appear a new element.
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 the click that appears dynamically does not do anything because the event was not associated with the new div. But still, why does the first click only take effect once? And how would I get what I want? Whenever I click any (.my_div
), dynamically generated or not appearing another?
Thanks @Sergio. That’s right... I accept in a few minutes
– Miguel
Instead of rewriting everything, just add clear.
– Miguel
Haa you just add the event to the window and only then specify the element for sure. It’s the same as
$(window).on('click', '.my-div', function() { ... })
right?– Miguel
I just noticed a little mistake in your... maybe I should edit the second
div
, the first to be generated comes withid=0
, should come withid=2
– Miguel
@Exact Miguel, with jQuery would be the delegation code. I added more info to the answer.
– Sergio
Thank you. Clarified
– Miguel