Here is the demo https://jsbin.com/kujeqefegi/edit?html,js,console,output There is a simple html and a script, part of which is responsible for adding new blocks, and part for deleting:
// Добавлене блоков var div = ''; var next_id = 3; add_block.onclick = function() { next_id++; var div = document.createElement('div'); div.id = 's'+next_id; div.className = 'text block'; var template = 'new - удали меня'; div.innerHTML = template; main.appendChild(div); }; //Удаление блоков main.onclick = function() { var DelButtons = document.querySelectorAll('.text.block'); var DelButtonsArray = Array.from(DelButtons); DelButtonsArray.forEach(function(button){ button.addEventListener('click', function(e) { document.getElementById(e.target.id).remove(); }) }); } Yes, I know that the .remove () method is not cross-browser, the question is different now, after removing the error in the console:
Uncaught TypeError: Cannot read property 'remove' of null at HTMLDivElement.
Is he trying to access an id that has just been deleted? How to prevent it?
main.onclickhang up other clicks in the loop .. as a result, the first click does not work, the second deletes one element, the third click - tries to kill two elements, and so on increasing ..... if you removemain.onclick = function() {and the last bracket}then it will work))) I really haven’t understood yet whatmain.onclickwas donemain.onclick- Alexey Shimanskyadd_blockhandleradd_blockcan writemain.appendChild(div); document.getElementById(div.id).addEventListener('click', function(e) { this.remove(); });main.appendChild(div); document.getElementById(div.id).addEventListener('click', function(e) { this.remove(); });.... but this is the fastest option ... - Alexey Shimanskydocument.getElementById(e.target.id)- you need to replace it withe.target- Grundy