[an error occurred while processing this directive]

JavaScript add row to table


This section illustrates you how to add a new row to the existing table using JavaScript.

You can see in the given example, we have created a table whose id is grabbed by the method document.getElementById(id) and stored it into the variable 'tbody'. The method createElement() creates the row element 'tr' and 'td'. As you already know that 'td' contains the table data and 'tr 'defines a row that contains the 'td' element. Now, the method appendChild(document.createTextNode()) adds the text node to the 'td' element as the table data. Then we have added the 'td' data to the row element 'tr'. When you load the page, you will get the table containing the columns Name and Address and a button 'Add row'. On clicking the button, a new row will be added to the table. 

Here is the code:

<h2>Add Row in JavaScript</h2>
function addRow(id){
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr")
var data1 = document.createElement("td")
var data2 = document.createElement("td")
data2.appendChild (document.createTextNode("Column2"))
<table id="table" cellspacing="0" border="1">
</table><button onclick="javascript:addRow('table')">Add row</button>

Output will be displayed as:

On clicking the button, a new row is added to the table:

Download Source Code:


[an error occurred while processing this directive]