Chinmay Sarupria Chinmay Sarupria - 19 days ago 5
Javascript Question

Why Javascript is not creating tables properly?

I am creating a program that connects to Firebase Realtime Database and displays the value in a table.

Her is my code:

var leadsRef = database.ref('leads/'+leadID);
var table = document.getElementById('remarksTable');

leadsRef.on('child_added', function(snapshot) {
var remark = snapshot.val().remark;
var timestamp = snapshot.val().timestamp;

var row = document.createElement('tr');
var rowData1 = document.createElement('td');
var rowData2 = document.createElement('td');
var rowData3 = document.createElement('td');
var rowDataText1 = document.createTextNode(remark);
var rowDataText2 = document.createTextNode(timestamp);
var rowDataText3 = document.createTextNode("Some text");
rowData1.appendChild(rowDataText1);
rowData2.appendChild(rowDataText2);
rowData3.appendChild(rowDataText3);
row.appendChild(rowData1);
row.appendChild(rowData2);
row.appendChild(rowData3);
table.appendChild(row);
});


leadID
is an ID which I get from the current url, it contains the correct value so no issues there, path is also absolutely right.

Here is the table code:

<table class="table table-bordered" id="remarksTable">
<tr>
<th><strong>Created On</strong></th>
<th><strong>Timestamp 2</strong></th>
<th><strong>Remarks</strong></th>
</tr>
<tr>
<td>12312313231</td>
<td>12312312312</td>
<td>just a remark.</td>
</tr>
</table>


Now, when I run the page, it connects to the Firebase database and loads the required values, creates table row and table data, attaches text to it and then finally attaches the row to table with the id of
remarksTable
but it is not creating rows properly. Please note the table is creating using Bootstrap.

This is how it looks:

enter image description here

As you can see, the first row displays fine but the next 2 rows which were created by javascript looks a bit different.

Answer

@Quentin is right, or you can simply add new rows this way:

var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData2 = row.insertCell(2);
rowData1.innerHTML = remark;
rowData2.innerHTML = timestamp;
rowData3.innerHTML = "some text";  

Here is a working demo

function addCells() {
  var table = document.getElementById("remarksTable");
  var row = table.insertRow();
  var rowData1 = row.insertCell(0);
  var rowData2 = row.insertCell(1);
  var rowData3 = row.insertCell(2);
  rowData1.innerHTML = "your remark";
  rowData2.innerHTML = "your timestamp timestamp";
  rowData3.innerHTML = "some text";
}
<table id="remarksTable" border=1>
  <tr>
    <td>first cell</td>
    <td>2nd cell</td>
    <td>3rd cell</td>
  </tr>
</table>
<button onclick="addCells()">Add New</button>

Comments