JavaScript: JavaScript function to add rows to a table
JavaScript DOM: Exercise-5 with Solution
Write a JavaScript function to add rows to a table.
Sample HTML file:
<!DOCTYPE html>
<html><head>
<meta charset=utf-8 />
<title>Insert row in a table - w3resource</title>
</head><body>
<table id="sampleTable" border="1">
<tr><td>Row1 cell1</td>
<td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td>
<td>Row2 cell2</td></tr>
</table><br>
<input type="button" onclick="insert_Row()" value="Insert row">
</body></html>
Sample Solution:
HTML Code:
<!-- Declaration of HTML document type -->
<!DOCTYPE html>
<!-- Start of HTML document -->
<html>
<!-- Start of head section -->
<head>
<!-- Declaring character encoding -->
<meta charset=utf-8 />
<!-- Setting title of the document -->
<title>Insert row in a table - w3resource</title>
</head>
<!-- Start of body section -->
<body>
<!-- Table element with id 'sampleTable' and border attribute -->
<table id="sampleTable" border="1">
<!-- First row of the table -->
<tr><td>Row1 cell1</td>
<td>Row1 cell2</td></tr>
<!-- Second row of the table -->
<tr><td>Row2 cell1</td>
<td>Row2 cell2</td></tr>
</table><br>
<!-- Button triggering the insert_Row function on click -->
<input type="button" onclick="insert_Row()" value="Insert row">
<!-- End of body section -->
</body>
<!-- End of HTML document -->
</html>
JavaScript Code:
// Function declaration for insert_Row
function insert_Row()
{
// Getting reference to the table with id 'sampleTable' and inserting a new row at index 0
var x=document.getElementById('sampleTable').insertRow(0);
// Inserting a new cell in the newly inserted row at index 0
var y = x.insertCell(0);
// Inserting a new cell in the newly inserted row at index 1
var z = x.insertCell(1);
// Setting inner HTML content of the first newly inserted cell
y.innerHTML="New Cell1";
// Setting inner HTML content of the second newly inserted cell
z.innerHTML="New Cell2";
}
Output:
Flowchart:
Live Demo:
See the Pen javascript-dom-exercise-5 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to get the value of the href, hreflang, rel, target, and type attributes of the specified link.
Next: Write a JavaScript function that accept row, column, (to identify a particular cell) and a string to update the content of that cell.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-dom-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics