Search code examples
javascripthtmldomappendchild

Need help changing appendChild to replaceChild


Is there an easy way to change this from appendChild to replaceChild?

This of course continuously adds more ele. Also for some reason it doesn't put the value inside the DIV or SPAN, seems to put below it.

var para = document.createElement("P");
var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;

para.appendChild(total);

document.getElementById("total_id").appendChild(para);

Its updating this:

<div class="prod_totals">Order Total: $<span id="total_id"></span></div>

Solution

  • you can simply use innerHTML instead of appendChild

    document.getElementById("total_id").innerHTML = parseFloat((subT + tax).toFixed(2));
    

    Because you're not inserting any user input values inside the total_id element and also as far as the question mentions, its data is not later passed to the server I think you'll be safe using the innerHTML here. But if for any reasons you'd still like to use replaceChild you could do it like this:

    var para = document.createElement("P");
    var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;
    
    para.appendChild(total);
    
    var existingText=document.getElementById("total_id").querySelector('p');
    if(existingText){
        document.getElementById("total_id").replaceChild(existingText, para);
    }
    else{
        document.getElementById("total_id").appendChild(para);
    }