javascript add a row to the table
var object = object.insertRow(index);
Parameters
index
Integer that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows group.
It uses the insertRow
method to add a row to the table.
myNewRow = document.all.myTable.insertRow()
Remarks
- The preferred technique for inserting a row is to add the row at the end of the rows collection.
- It is faster to add a row at the end of a table than somewhere in the middle.
- To add a row at the end of the collection, specify the
-1
value or the length of the rows collection minus1
.
body row
<table> <thead> <tr> <th>Name</th> <th>Job</th> </tr> </thead> <tbody id="table"> <!-- Your table rows will go here --> </tbody> </table>
- First, we create a
tbody
variable. It grabs thetbody
element with the table ID. - So we can talk to it later when we want to add our table rows to it.
var tbody = document.getElementById('table');
var datas = [ { "name": "Adam", "job": "Accountant" },{ "name": "Olivia", "job": "Magician" },{ "name": "Oliver", "job": "Dentist" },{ "name": "Ava", "job": "Teacher" } ];
We Use forEach loop for that
datas.forEach(function(data) { // Do Something });
Then we create another variable, tableRow.
It creates a new line for each person.
var tableRow = tbody.insertRow(-1);
Use
for
loop within aforEach
loop !
And this one looks different because instead of looping through items in a list
This time, we’re looping through the attributes within our object.
for (i in data) { var tableCell = tableRow.insertCell(-1); tableCell.innerHTML = data[i]; }
- That
(-1)
is just special to this particularinsertCell()
method and means that we want the table cell to be added to the end. - This is something I’d never seen before and had to Google. We’re learning together!
Here’s the complete Code
var tbody = document.getElementById('table'); datas.forEach(function(data) { var tableRow = tbody.insertRow(-1); for (i in data) { var tableCell = tableRow.insertCell(-1); tableCell.innerHTML = data[i]; } })