How to use insertAdjacentHTML() In Javascript
In this approach, we are using the insertAdjacentHTML() method in JavaScript to dynamically insert a rown in the HTML table.
Syntax:
node.insertAdjacentHTML(specify-position, text-to-enter)
Example: The below example uses insertAdjacentHTML() to insert a row in an HTML table using JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Example 2</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 rgb(255, 0, 0);
padding: 8px;
}
</style>
</head>
<body>
<h3>
Using insertAdjacentHTML() to insert a Row
<br/> dynamically inside an HTML table.
</h3>
<table id="tab">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>GFG 1</td>
<td>30</td>
</tr>
<tr>
<td>GFG 2</td>
<td>25</td>
</tr>
</tbody>
</table>
<br/>
<button onclick="insertFn()">
Insert Row
</button>
<script>
function insertFn() {
const newRow =
`<tr>
<td>GFG 3</td>
<td>34</td>
</tr>`;
document.getElementById('tab').
getElementsByTagName('tbody')[0].
insertAdjacentHTML('beforeend', newRow);
}
</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()