I have table in HTML:
And I have button in HTML also.By clicking on button a new cell appears each time. Every new cell has class of course. Then I want to click on cell so that new div appears.
It should work like this:
cell_1 (class xxx) can create div1
cell_2 (class xxx) can create div2
etc.
The problem is: I cannot address to class xxx of these cells correctly. I have tried to solve it by adding new script in the end of the addEventListener code like this:
let popupScript = document.createElement ("script");
popupScript.src = "newscript.js";
document.body.appendChild(popupScript);
And in this newscript I can address to dynamically created class xxx. But the problem remains: if I create 5 cells and then click on the cell №1, it works like I click 5 times on cell №1.
Also I have tried to use MutationObserver. But the problem remains.
Then I decided to check it another way: In HTML:
<table>
<tr>
<td class="textClass">1</td>
<td class="textClass">2</td>
<td class="textClass">3</td>
<td class="textClass">4</td>
</tr>
<tr>
<td id="click_button">GO CLICK</td>
</tr>
</table>
In JavaScript:
for (let g=0; g<4; ++g) {
document.querySelectorAll(".textClass")[g].addEventListener ("click", function() {console.log (g)});
}
Now g in console show the correct number of clicking. One click - one number.
But if I put this code in JavaScript:
let x = 0;
document.getElementById ("click_button").addEventListener ("click", function() {
let y = document.createElement ("div");
document.body.appendChild (y);
x++;
});
let observer = new MutationObserver (function () {
for (let g=0; g<x; ++g) {
document.querySelectorAll(".textClass")[g].addEventListener ("click", function() {console.log (g)});
}
});
observer.observe (document.body, {childList: true});
the problem remains. And if you click 4 times on "GO CLICK" and then click on 1st cell, in console you will see (4)0.
So, what is wrong?