Remove nodes created using EventListener

1

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

    
asked by Franco Del Castillo 02.08.2017 в 06:00
source

2 answers

1

The error is because you try to access an element that has not been added to document . then the line

var deleteUnit = document.getElementById('newBox');

It will return null , therefore you will not be able to add the evento . If you want the element with id newBox to exist, you will have to call the createBox() method so that it can exist in document .

createBox();
var deleteUnit = document.getElementById('newBox');
deleteUnit.addEventListener('click', deleteBox);

Now if you want to add the same evento to the elements created with the button, you must add the addEventListener within the createBox() method since in principle JavaScript was already executed and only the listener was added to the element that I create (to the elements with the id or class that exist in the sun) when calling the function manually.

Another observation is that within the delete method it is not necessary to search again for the element with getElementById , the element that was given click can be referenced with this directly.

Además como recomendación el ID debe ser Único en el DOM , so in my example I use getElementsByClassName that returns a collection and with [0] I access the first element that would be created. These lines are left in the code in case you want to show a box by default when loading the document .

Final code

function createBox() {
  var box = document.createElement('div');
  box.className = 'box';
  box.addEventListener('click',deleteBox);
  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() {
 this.remove();
}

/* EVENTO PARA CLIC CAJA Y REMOVER
aquí invoco por el id newBox que asigné más arriba */
createBox();
var deleteUnit = document.getElementsByClassName('box')[0];
deleteUnit.addEventListener('click', deleteBox);
.box{
    width: 200px;
    height: 200px;
    background: #ccc;
    margin:1em;
}
<div class="container" id="container">  
</div>
<input type="button" id="btn" value="Agregar"/>
    
answered by 02.08.2017 / 06:22
source
0

What you would have to do is the following, to the new element that you created to add the onClick method in the html tag so that it executes the function delete box, you would do the following:

// FUNCION PARA CREAR CAJA
function createBox() {
  var box = document.createElement('div');
  box.className = 'box';
  box.id = 'newBox';
// Evento para eliminar la caja
  box.onclick = deleteBox();
  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() {
 this.remove();
}

Someone to try that and tell me what is wrong, because I can not prove it because I did it from the cell phone

    
answered by 02.08.2017 в 06:43