I'm trying to add a row to a HTML table in pure JS as follows,
var tbody = document.getElementsByClassName('table1_out').getElementsByTagName("TBODY");
var row = document.createElement("TR");
var td1 = document.createElement("TD")
var strHtml1 = "<?php echo $addNewCurrencyPOST["id"] ?>";
td1.innerHTML = strHtml1;
var td2 = document.createElement("TD")
var strHtml2 = "<div class='led on'></div>";
td2.innerHTML = strHtml2;
var td3 = document.createElement("TD")
var strHtml3 = "<?php echo $addNewCurrencyPOST["symbol"] ?>";
td3.innerHTML = strHtml3;
var td4 = document.createElement("TD")
var strHtml4 = "<?php echo $addNewCurrencyPOST["symbolhtml"] ?>";
td4.innerHTML = strHtml4;
var td5 = document.createElement("TD")
var strHtml5 = "<?php echo $addNewCurrencyPOST["usdrate"] ?>";
td5.innerHTML = strHtml5;
var td6 = document.createElement("TD")
var strHtml6 = "<?php echo $addNewCurrencyPOST["eurrate"] ?>";
td6.innerHTML = strHtml6;
var td7 = document.createElement("TD")
var strHtml7 = '';
td7.innerHTML = strHtml7;
// append data to row
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
row.appendChild(td6);
row.appendChild(td7);
// append row to table
tbody.appendChild(row);
And this is the structure of the table,
<div class="table1_out">
<table>
<thead>
<tr>
<th>Id</th>
<th>Status</th>
<th>Symbol</th>
<th>Symbol html</th>
<th>Exchange rate EUR</th>
<th>Exchange rate USD</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>EUR</td>
<td><div class="led on"></div></td>
<td>€</td>
<td>&euro;</td>
<td>1</td>
<td>1.319810</td>
<td><input type="button" value="Edit" onclick="document.location.href='/backoffice_dev.php/currency/edit/EUR';"></td>
</tr> </tbody>
</table>
</div>
But it is throwing the error:
TypeError: tbody.appendChild is not a function
That's because your tbody is actually an array-like object, as in [<tbody>]:
var tbody = (...).getElementsByTagName("TBODY");
You're using "get Elements", which returns a node list. Take the first of those:
var tbody = (...).getElementsByTagName("TBODY")[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With