A few weeks ago I started with JavaScript
, I just learned how to use EventListener
, please help me, how can I remove a node created using EventListener
?.
In the example I will show below I assign an EventListener to a button to generate nodes (div boxes), what I want is to be able to click on each box created to remove it.
I made the following code but it is not working to remove the created nodes, it only works if I have the div boxes added manually in the HTML and calling them with their id. Here the code:
// FUNCION PARA CREAR CAJA
function createBox() {
var box = document.createElement('div');
box.className = 'box';
box.id = 'newBox';
var container = document.getElementById('container');
container.appendChild(box);
}
// EVENTO PARA CLIC BOTÓN Y CREAR CAJA
var createUnit = document.getElementById('btn');
createUnit.addEventListener('click', createBox);
// FUNCION PARA REMOVER CAJA
function deleteBox() {
var deleteBox = document.getElementById('newBox').remove();
this.remove();
}
/* EVENTO PARA CLIC CAJA Y REMOVER
aquí invoco por el id newBox que asigné más arriba */
var deleteUnit = document.getElementById('newBox');
deleteUnit.addEventListener('click', deleteBox);
I see the error in the console:
Uncaught TypeError: Can not read property 'addEventListener' of null