javascript add to table code example
Example 1: how to create table using DOM
function render(){
for (let i = 0; i < allMovie.length; i++) {
tr = document.createElement('tr');
tr.setAttribute("class", "mainTR");
table.appendChild(tr);
var td1 = document.createElement('td');
td1.textContent = allMovie[i].MovieName11;
td1.setAttribute("class", "td1");
tr.appendChild(td1);
var td2 = document.createElement('td');
td2.textContent = allMovie[i].selectPlatform11;
td2.setAttribute("class", "td2");
tr.appendChild(td2);
var td3 = document.createElement('td');
td3.textContent = allMovie[i].randomRate;
td3.setAttribute("class", "td3");
tr.appendChild(td3);
var td4 = document.createElement('td');
td4.textContent = allMovie[i].monthlyPay11;
td4.setAttribute("class", "td4");
tr.appendChild(td4);
var td5 = document.createElement('td');
td5.setAttribute("id", "td5");
td5.innerHTML = `<button onclick=remove(this.parentElement)> X </button>`
tr.appendChild(td5);
}
}
Example 2: javascript append to html table tr
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
</script>