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?

  • You are inside one click of main.onclick hang 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 remove main.onclick = function() { and the last bracket } then it will work))) I really haven’t understood yet what main.onclick was done main.onclick - Alexey Shimansky
  • If you want to click on the newly created element, then at the end of the add_block handler add_block can write main.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 Shimansky
  • @ Alexey Shimansky Concerning the first comment: I tried to remove main.onclick and the bracket, then the first blocks (that existed) will be deleted and there are no new jsfiddle.net/aur559bu errors in the console, but there are no any - fosh4455
  • jsbin.com/foyuceluqa/1/edit?html,js,console,output ...... you need to hang handlers on new ones ... and so after each addition of the block you hang more handlers in the cycle and they increase in progression - Alexey Shimansky
  • in fact, you just don't need document.getElementById(e.target.id) - you need to replace it with e.target - Grundy

0