Search code examples
javascripthtmldomevent-listenerqueryselector

How to replace AdjacentHTML instead of creating another Instance of AdjacentHTML


I am developing a very simple application that tracks a number or barcodes used.

Once the quantity of the barcodes are calculated I display it to the UI using the Javascript insertAdjacentHTML function, creating a div with the required HTML, although I just can't seem to find a method on how to replace the DIV each time instead of it creating another instance and another and another.

I think it might be a scope issue, but I could not find a solution.

const myForm = document.getElementById("form_barCodeAdmin");

myForm.addEventListener("submit", (e) => {
    let startRange, endRange, quantity;

    e.preventDefault(); // Prevents web page from reloading.

    startRange = document.getElementById("start__range").value;
    endRange = document.getElementById("end__range").value;



    if(endRange > startRange){

        quantity = endRange - startRange;

        let html = `<div class="alert alert-warning" id="quantity__range">Quantity Barcodes: %quantity% </div>`;

        replacedHTML = html.replace('%quantity%', quantity);
        document.getElementById("range__Results").insertAdjacentHTML('beforeend', replacedHTML);


        // if html is not empty then delete Node and run Insert html function. Else run Function. 

    } else {
        console.log("Please enter a smaller starting range than the end range");
    };

});

Solution

  • If you want to replace all the content of #range__Results just use .innerHTML = replacedHTML instead of inserting it.

    If there's more content and you only want to replace the #qunantity_range that you added before you could check if it's present and remove it before inserting the new one

    let currentQuantityRange = document.getElementById('quantity_range')
    if (currentQuantityRange) currentQuantityRange.remove()
    

    Or, you could check if the div exists and replace it's content instead of adding it

    let currentQuantityRange = document.getElementById('quantity_range')
    if (currentQuantityRange)
      currentQuantityRange.innerHtml = `Quantity Barcodes: ${quantity}`
    else {
      let html ....