How to Create a Table With jQuery

Anika Tabassum Era Feb 02, 2024
  1. Create a Table With jQuery by Taking the Table Content as a String
  2. Create a Table With jQuery by Creating a Table Instance
How to Create a Table With jQuery

With the help of the jQuery library, we can add new table rows to our content and create the table element. We will go for basic loop work to ensure our data or output pattern is stacked in a table format.

We will examine two examples, one that will take the table tags and contents as a string. Later on, appending it will configure it as a table in the HTML body.

However, creating table elements as strings can hamper later customization. So, in our second example, we will create an instance of a table element, and thus by specifying the attributes (id, class), we can change the table contents properties.

Let’s give a thorough check to understand.

Create a Table With jQuery by Taking the Table Content as a String

Here, we will take a variable to store the table elements start tag, add the contents, and the end tag. In the next step, we will append this sum or collection of strings to the div we considered.

The basic problem would be we are unable to reinitialize the properties for table data or table rows. Let’s check the code lines.

Code Snippet:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div id="tab"> </div>
<script>
   var content = "<table>"
   for(i=0; i<3; i++){
       content += '<tr><td>' + 'output ' +  i + '</td></tr>';
   }
   content += "</table>"
   
   $('#tab').append(content);
</script>

Output:

Create Table by Taking Table Content as String

Create a Table With jQuery by Creating a Table Instance

We will consider creating the instance for a table along with its id and class attribute. Later, based upon preference, we can change the properties.

The code fences describe this more explicitly.

Code Snippet:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div id="tab"> </div>
<script>
   var table = $('<table>');
   for(i=0; i<3; i++){
      var row = $('<tr>').text('output ' + i).addClass('rows');
      row.addClass('rows').css({'color':'red'});
      table.append(row);
   }
   
   $('#tab').append(table);
</script>

Output:

Create Table by Creating Table Instance

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - jQuery Table