Delete ALL nodes children of a div

3

I am developing an application and I have encountered the following problem:

  • By pressing the "Analyze" button, I dynamically create JavaScript with different div containing their own table with data. The problem arises that pressing the same button a second time "duplicates" the data in the tables.

  • To avoid the problem before the creation of the div I check if they are created or not, and if they exist, I delete all the elements it contains ("children") in order to recreate them but with the updated information.

  • The thing is that I can not get the div duplicates, but within these the information in the table itself is duplicated and I can not find a way to avoid it.

I leave the initial HTML (in the div "background" is where the new div with their tables are inserted):

function GetInformation() {
  var section = ["A", "B", "C", "D", "F"];
  var div = document.getElementById("top-mail-box");

  //<---------- Compruebo si existen los div --------->

  if (div != null) {
    var parent = div.parentElement;
    parent.removeChild(div);
  } else {
    alert("No existe la caja previamente creada.");
  }


  //<---------- Resto del código que me inserta los datos de las tablas --------->
  $.ajax({
    url: '../GetInformation',
    type: 'GET',
    datatype: 'text',
    success: function(json) {

      var content = document.createElement("div");
      content.className = "top-mail-box";
      content.id = "top-mail-box";
      document.getElementById("background").appendChild(content);

      for (i = 0; i < section.length; i++) {

        //SECTION (creación de los distintos Div)

        var meanDiv = document.createElement("div");
        meanDiv.className = "accordion-group";
        meanDiv.id = "meanDiv";
        var firstDiv = document.createElement("div");
        firstDiv.className = "accordion-heading";

        var firstA = "<a class='section_title'>" + section[i] + "</a>";
        var secondA = "<a class='section_icon' data-toggle='collapse' onclick='Section(" + "\"" + section[i] + "\"" + ")'>" +
          "<i id ='" + section[i] + "-icon' class='glyphicon glyphicon-chevron-down'>" + "</i>" +
          "</a >";
        firstDiv.innerHTML = firstA + secondA;

        var secondDiv = document.createElement("div");
        secondDiv.className = "accordion-body collapse";
        secondDiv.id = section[i];
        var internalsecondDiv = document.createElement("div");
        internalsecondDiv.className = "accordion-inner";

        var tablesecondDiv = document.createElement("table");
        tablesecondDiv.className = "table table - striped table - condensed";
        tablesecondDiv.id = section[i] + "table";

        internalsecondDiv.appendChild(tablesecondDiv);
        secondDiv.appendChild(internalsecondDiv);

        meanDiv.appendChild(firstDiv);
        meanDiv.appendChild(secondDiv);

        document.getElementById("top-mail-box").appendChild(meanDiv);

        //THEAD (creación del encabezado de las tablas)

        var theadElement = document.createElement("thead");
        var trElement = document.createElement("tr");
        trElement.className = "columns";
        var row = "<th>Category</th><th>Key</th><th>Value</th><th>Description</th>";
        trElement.innerHTML = row;
        theadElement.appendChild(trElement);
        document.getElementById(section[i] + "table").appendChild(theadElement);

        //TBODY (inserción de los datos en cada tabla)

        var tbodyElement = document.createElement("tbody");

        for (j = 0; j < json.length; j++) {
          if (json[j].ConfigFile == files[i]) {
            var trElementBody = document.createElement("tr");
            trElementBody.id = "row";
            var tdElement = "<td>" + json[j].Category + "</td><td>" + json[j].Key + "</td><td>" + json[j].Value + "</td><td>" + json[j].Description + "</td>";
            trElementBody.innerHTML = tdElement;
            tbodyElement.appendChild(trElementBody);
          }
        }

        document.getElementById(section[i] + "table").appendChild(tbodyElement);
      }
    },
    error: function(xhr, status) {
      alert(xhr + " : " + status);
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mail-box">
  <div id="background" class="background">

  </div>
  <div class="pbottom">
    <div class="pull-right">
      <input type="submit" value="Analyse" class="btn btn-primary correct" onclick="GetInformation()" />
    </div>
  </div>
</div>

It would also be good for me to always refresh the page initially and then call the GetInformation () function but I can not make it run sequentially.

    
asked by Ace 10.04.2018 в 22:37
source

3 answers

1

can use the property to replace, that I can replace if it finds a div that is already defined and avoid the duplicator, here is an example

<p id="demo">Visit Microsoft!</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("Microsoft", "W3Schools");
    document.getElementById("demo").innerHTML = res;
}
</script>
    
answered by 11.04.2018 в 03:30
0

if you are using jquery why do not you do this

var div = $("#top-mail-box");

  if (div.length > 0) {
    div.find(".accordion-group").remove();
  } else {
    alert("No existe la caja previamente creada.");
  }

You recover the container and when it does, find the children with x name and then delete them or if it is only that information you have you can do

$("#top-mail-box").html("");

and thus you delete all the information of es

    
answered by 11.04.2018 в 02:00
-1

Edit In the photo that you include there are many div with the same ID , without seeing the generated code it is difficult to know with precision, but surely there is only one of the div s that behaves well and the rest remains the same.

the item IDs must all be different, try adding the element's index as part of the name (for example: id="MeanDiv-1" , id="AMI-1" , id="AMITable-1" ..., id="MeanDiv-2" etc ...), or use a data-id attribute to identify it and change the content instead of deleting it.

original To delete children with a single level of nesting I use this snipet

while (element.firstChild){
  element.removeChild(element.firstChild);
};
element.parentNode.removeChild(element);

for more levels we would have to do recursive as in this answer link

note recursion is only necessary if the elements are very heavy in memory and you do not want to wait for the garbage collector to remove the "grandchildren and their descendants" by not finding references.

    
answered by 11.04.2018 в 05:00