Remove HTML5 DIV item content

0

What is the correct way to remove the content of an element <div id="root"></div> of HTML 5 if this element contains other elements <div></div> , I have tried these two options and both work, but I would like to know which is correct or the difference between using one or the other.

First form:

var div = document.getElementById('root');
while (div.firstChild) {
    div.removeChild(div.firstChild);
}

Second form:

document.getElementById('root').innerHTML = '';
    
asked by nullptr 23.11.2017 в 15:44
source

3 answers

3

In theory the function that does what you want specifically that is to erase the nodes is the first way:

var div = document.getElementById('root');
while (div.firstChild) {
    div.removeChild(div.firstChild);
}

already in case you have too many children within the div you will be delayed a little more running the cycle, but with the innerHTML you eliminate everything directly in a generic and immediate way. It's already based on your taste.

    
answered by 23.11.2017 в 16:56
0

Here I leave an option and delete in this case all nodes children greetings I hope I help you

function aliminarHijos() {
  var padre = document.getElementById("padre");
  for (var i = 0; i < padre.children.length; i++) {
    var hijo = padre.children[i]
    padre.remove(hijo)
  }
}
#padre {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: auto;
  background: rgb(245, 245, 245);
}
#padre > div {
  background: rgb(255, 255, 255);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0px 3px 15px 0px rgba(0, 0, 0,.1);
  width: 100%;
  height: 200px;
  margin: 10px;
}
<button onclick="aliminarHijos()" type="button" name="button">Eliminar Hijos</button>

<div id="padre">
  <div class="hijo1">
    hijo 1
  </div>
  <div class="hijo2">
    hijo 2
  </div>
   <div class="hijo1">
    hijo 3
  </div>
  <div class="hijo2">
    hijo 4
  </div>
</div>
    
answered by 23.11.2017 в 16:25
0

const e = document.getElementById("main"),
      deleted = [];
Array.from(e.childNodes).forEach( child => {e.removeChild(child); deleted.push(child.tagName);});


console.log(deleted); // Ver eliminados
<div id="main"><h1>Hola</h1><br><i>wow</i><p> !! </p><hr></div>
    
answered by 24.11.2017 в 00:14