Delete JavaScript DIV elements

1

I'm trying to remove all the elements of the class cupcake from my dom to repaint them based on a filter.

I'm doing;

let cupcakes= document.getElementsByClassName("cupcake");
alert(cupcakes.length);
for(element of cupcakes){
console.log(element);
container.removeChild(element);
console.log(element);
console.log("-------------------------------------------------------");
}

The length of elements that I recover is exactly what I need and the elements as well, but I do not understand that I only delete the odd ones, the output of the previous code is as follows;

Only shows the odd elements Why? I need to delete all of them, each one of those that the loop goes through, if I delete the line of removeChild it prints all the objects.

    
asked by Hector Lopez 05.12.2018 в 20:01
source

2 answers

2

The problem is that the getElementsByClassName function returns a "live" list of HTML elements, what I mean is that if you delete an HTML element you also remove it from the list and this interferes with the iteration because the indexes change. One way to fix it is to create a copy of the list before iterating.

var container = document.getElementById('container');

document.getElementById('boton').addEventListener('click', (e) => {
  let cupcakes = Array.prototype.slice.call(document.getElementsByClassName("cupcake"), 0);
  
  for(element of cupcakes){
    console.log(element);
    element.remove();
  }  
});
<div id="container">
  <div id="1" class="cupcake">1</div>
  <div id="2" class="cupcake">2</div>
  <div id="3" class="cupcake">3</div>
  <div id="4" class="cupcake">4</div>
  <div id="5" class="cupcake">5</div>
  <div id="6" class="cupcake">6</div>
  <div id="7" class="cupcake">7</div>
  <div id="8" class="cupcake">8</div>
  <div id="9" class="cupcake">9</div>
  <div id="10" class="cupcake">10</div>
</div>

<button id="boton">Probar</button>
    
answered by 05.12.2018 / 20:19
source
2

If you want to eliminate all the elements div with a specific class I recommend you use JQuery , I leave you an example where there is a div with a class other than cupcake :

$( "div" ).remove( ".cupcake" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1" class="cupcake">Prueba 1</div>
<div id="2" class="cupcake">Prueba 2</div>
<div id="3" class="cupcake">Prueba 3</div>
<div id="4" class="cupcake">Prueba 4</div>
<div id="5" class="cupcakePrueba">Prueba 5</div>
<div id="6" class="cupcake">Prueba 6</div>

I use the remove function to remove them from dom . I leave the documentation in case you need it: link . Greetings.

    
answered by 05.12.2018 в 20:17