Computer >> Computer tutorials >  >> Programming >> Javascript

How to add rows to a table using JavaScript DOM?


To add rows to a table with JavaScript, use the DOM method insertRow().

Example

You can try to run the following code to learn how to add a row to a table one at a time −

<!DOCTYPE html>
<html>
   <head>
      <script>
         function rowFunction(x) {
            var a = document.getElementById(x).insertRow(0);
            var b = a.insertCell(0);
            var c = a.insertCell(1);
            b.innerHTML = c.innerHTML = "row";
         }
      </script>
   </head>
   <body>
      <table style="border:2px solid black" id="newtable">
         <tr>
            <td>One</td>
            <td>Two</td>
         </tr>
         <tr>
            <td>Three</td>
            <td>Four</td>
         </tr>
         <tr>
            <td>Five</td>
            <td>Six</td>
         </tr>
      </table>
      <p>
         <input type="button" onclick="rowFunction('newtable')" value="Add a row">
      </p>
   </body>
</html>