How to Create a Table in JavaScript | Easy Way

Create a Table in Javascript

In this article, we see how to create a table in javascript. Remember that, we don’t use javascript to create a complete HTML page. On the fly, if we want to generate some HTML elements and display some content, we are going to take the help of JavaScript because it is used to add behavior to HTML pages not used to generate a complete HTML page. For example, if you click on a button you want to change some text and make it highlighted then you are going to use JavaScript in that situation.

  1. To create a table, you can use the <table> tag within the printing statement in JS. Don’t forget to set a border for the table, Because your table will show only if you give a border.
  2. If you want to create a row, you can use the <tr> tag inside the <table> tag.
  3. If you want to create a data cell inside the row, you can use the <td> tag inside the <tr> tag as in the above code.
  4. Save and see your output, the table will displayed successfully.

Code:

document.write("<table border='1'><tr><td>1</td><td>2</td></tr>
                   <tr><td>1</td><td>2</td></tr></table>");

It is not necessary to write all the code in a single “document. write” print statement. Of course, you can use a single print statement and display a complete HTML table. Instead of that, we can use multiple “document.write” print statements also. So, that we can manage the code properly as well as it is easy for us to make the code more readable. If we write everything in a single printing statement then later if you had more table rows, then it becomes more cumbersome as well as difficult to manage, difficult to understand, and difficult to modify. So, instead of writing like the above code, we can use it to write more than one printing statement like the below code.

READ ALSO  Delete Operator in JavaScript | Explained

Code:

document.write("<table border='1'>");
   document.write("<tr>");
      document.write("<td>1</td>");
      document.write("<td>2</td>");
   document.write("</tr>");
   document.write("<tr>");
      document.write("<td>1</td>");
      document.write("<td>2</td>");
   document.write("</tr>");
document.write("</table>");

Output:

create a table in javascript

Leave a Reply