I'm new to javascript but still tend to try fixing an issue myself. However, I got frustrated because the same function works for a slightly different HTML without tbody and thead.
The error I get is --> Uncaught TypeError: Cannot read property 'insertRow' of null.
Where am I wrong? Also probably there is a better way to add a table row? I tried .append but it did not work for me.
HTML
<table class="table table-striped myTable">
<button class="btn btn-primary btn-lg" id="addTableRow">Add table row</button>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>City</th>
<th>Sex</th>
<th>Date</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr id="firstRow">
<td>John</td>
<td>Morgan</td>
<td>[email protected]</td>
<td>London</td>
<td>Male</td>
<td>09.12.14</td>
<td>04:17 a.m.</td>
</tr>
</tbody>
</table>
JavaScript
$("#addTableRow").click( function(){
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = "Text-1";
cell2.innerHTML = "Text-2";
cell3.innerHTML = "Text-3";
cell4.innerHTML = "Text-4";
cell5.innerHTML = "Text-5";
cell6.innerHTML = "Text-6";
});
Just a few typos, missing ID on your table and mixing jQuery incorrectly.
$("#addTableRow").click( function () {
var row = $("<tr>");
row.append($("<td>Text-1</td>"))
.append($("<td>Text-2</td>"))
.append($("<td>Text-3</td>"))
.append($("<td>Text-4</td>"))
.append($("<td>Text-5</td>"))
.append($("<td>Text-6</td>"))
.append($("<td>Text-7</td>"));
$("#myTable tbody").append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="myTable" class="table table-striped myTable">
<button class="btn btn-primary btn-lg" id="addTableRow">Add table row</button>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>City</th>
<th>Sex</th>
<th>Date</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr id="firstRow">
<td>John</td>
<td>Morgan</td>
<td>[email protected]</td>
<td>London</td>
<td>Male</td>
<td>09.12.14</td>
<td>04:17 a.m.</td>
</tr>
</tbody>
</table>
Not strictly related to the question, but I ended up here for having the "Uncaught TypeError: table.insertRow is not a function" error. You may be having the same problem. If so:
If you want to use
row.insertCell(0);
and you receive the former error, be sure not to get the element by using jquery:
DO NOT
let table = $("#peopleTable");
let newRow = table.insertRow(0);
DO
let table = document.getElementById("peopleTable");
let newRow = table.insertRow(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