javascript – Delete previously created elements

Question:

I am making a form which, when receiving a request through Ajax, and depends on the option chosen by the user (these options come through a select ), store their values ​​in a div .

  • HTML:
 <select class="custom-select" id="lista" name="lista">
    <option selected value="0">Seleccionar...</option>
    <option value="1">Opcion #1</option>
    <option value="2">Opcion #2</option>
</select>
  • Javascript:
    $("#lista").change(function(){
        var lista = $("#lista").val();
        var datos = new FormData();
        datos.append("lista", lista); 

        $.ajax({
            url: "....",
            method:"POST",
            data: datos,
            cache: false,
            contentType: false,
            processData: false,
            dataType:'JSON',
            success: window.respuesta
        });
    });
  • Response function where the div is created:
function respuesta(respuesta){
    let fila = $(".f-indicadores");

    for(let i = 0; i < respuesta.length; ++i)
    {
        fila.append('<div class="col-12"><p>' + respuesta[i].BANCO + '</p></div>');
    }
}

These div are created using the append method as seen above and stored here:

<div class="row f-indicadores">
   <div class="col-12" id="content"></div>
</div>

But then when it is created, and request another request (that is, the user chooses another option in the select), it recreates other div above those already created previously.

My question is, how would it be possible to delete the previously created div ?

Answer:

you can do it like this:

function respuesta(respuesta){
    let fila = $(".f-indicadores"); //selecciona la fila
    fila.text(" "); // el metodo text() eliminas los divs interno

    for(let i = 0; i < respuesta.length; ++i){
        fila.append('<div class="col-12"><p>' + respuesta[i].BANCO + '</p></div>');
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row f-indicadores">
   <div class="col-12" id="content">holas</div>
</div>
Scroll to Top