I’m currently writing some pretty basic code for a shopping cart on a webpage (it’s for an assignment, and I’m restricted to JS, HTML and CSS)
I’m trying to fill in a table that fills with whatever is contained in a series of arrays (Name[], Quantity[] and Sum[]). I already have a for the table, and the div I’m writing into is within a table. Yet whenever I run the webpage, the table and its contents are always written before my as a seperate table.
I’m not entirely sure on what’s gone wrong, so here’s the code:
HTML:
<table border="1">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Sum Total</th>
</tr>
</thead>
<div id="cart"></div>
</table>
JavaScript:
function ViewShoppingCart(){
document.getElementById("cart").innerHTML = ""; // Empties the cart
for (var i=0; i<Name.length; i++) {
var tr= document.createElement("tr");
document.getElementById("cart").appendChild(tr);
var td= document.createElement("td");
td.appendChild(document.createTextNode(Name[i]));
tr.appendChild(td);
var td1= document.createElement("td");
td1.appendChild(document.createTextNode(Quantity[i]));
tr.appendChild(td1);
var td2= document.createElement("td");
td2.appendChild(document.createTextNode("\u00A3"+parseFloat(Sum[i]).toFixed(2)));
tr.appendChild(td2);
}
}
<div>is not a valid child of<table>. The browser is rearranging the DOM that represents your markup in an attempt to make sense of it.If you want a div in a table, that div will have to be in a
<th>or<td>.