How to use insertRow() and insertCell() In Javascript
In this approach, we are using the insertRow() and insertCell() methods in JavaScript to dynamically insert a new row into an HTML table.
Syntax:
tableObject.insertRow(index)
tablerowObject.insertCell(index)
Example: The below example uses insertRow() and insertCell() to insert a row in an HTML table in JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Example 1</title>
<style>
body {
text-align: center;
font-family: Arial, sans-serif;
}
h3 {
margin-bottom: 20px;
}
table {
margin: 0 auto;
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 8px;
}
</style>
</head>
<body>
<h3>
Using insertRow() and insertCell()
<br/> to add a new row in HTML table.
</h3>
<table id="tab">
<thead>
<tr>
<th>Subject</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>Python</td>
<td>56</td>
</tr>
<tr>
<td>JS</td>
<td>60</td>
</tr>
</tbody>
</table>
<br/>
<button onclick="insertFn()">
Insert Row
</button>
<script>
function insertFn() {
const table = document.getElementById("tab").
getElementsByTagName('tbody')[0];
const newRow = table.insertRow();
const cell1 = newRow.insertCell(0);
const cell2 = newRow.insertCell(1);
cell1.innerHTML = "CSS";
cell2.innerHTML = "67";
}
</script>
</body>
</html>
Output:
How to Insert a Row in an HTML Table in JavaScript ?
In JavaScript, we can insert a row dynamically in the HTML table using various approaches. JavaScript provides us with different methods to accomplish this task as listed below.
Table of Content
- Using insertRow() and insertCell()
- Using insertAdjacentHTML()