LeeAlexander
LeeAlexander

Reputation: 49

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>

Upvotes: 1

Views: 4920

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

There's no need to use .replaceChild here, you can simply check if the element was already created before trying to update it.

Note that you were trying to insert a p element inside a span which is wrong and is not valid HTML markup, you can see in the span documentation that its possible content is only Phrasing content, so you better use another span.

This is how should be your code:

var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
  para = document.createElement("span");
}
var total = parseFloat((subT + tax).toFixed(2));
para.innerText = total;
document.getElementById("total_id").appendChild(para);

And here's a Demo:

var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
  para = document.createElement("span");
}
var total = new Date();

para.innerText = total;

document.getElementById("total_id").appendChild(para);
<div class="prod_totals">Order Total: $<span id="total_id"></span></div>

Upvotes: 0

Amin Jafari
Amin Jafari

Reputation: 7207

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);
}

Upvotes: 2

Related Questions