Explain Codes LogoExplain Codes Logo

Create table with jQuery - append

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Sep 3, 2024
TLDR

Building tables like a pro! Get a row with two cells into your table with ID #myTable:

$("<tr>").append($("<td>").text("Cell 1"), $("<td>").text("Cell 2")).appendTo("#myTable");

Upgrading your table building skills

Because sometimes we need more than just a row, let's amplify our skills to build more advanced and dynamic tables.

Create your table dynamically

Kick-start the creation with a jQuery object for your table:

var table = $('<table>').addClass('yourCustomClass'); // Classy table coming up!

Row, row, row your table

Using for or each loop, we can build as many rows as we need like a human-powered assembly line:

for (let i = 0; i < rowCount; i++) { let row = $('<tr>').addClass('rowClass'); // New row, feeling like a rockstar, aren't we? for (let j = 0; j < colCount; j++) { row.append($('<td>').text(`Row ${i} Cell ${j}`)); // Populating cells with loop magic. } table.append(row); // Level up! We just built a row! }

Improving performance

Hate waits? So does your browser. Use document.createDocumentFragment() to cut down on annoying page reflows:

var fragment = document.createDocumentFragment(); $(table).find('tr').each(function() { fragment.appendChild(this); // This... is... Fragment!! }); table.get(0).appendChild(fragment);

Final table move

Your table's ready to take the stage! Be the showstopper:

$("#container").append(table); // Drumroll please... here's your table!

Let's get down to business!

Table creation is not just concatenating <table>, <tr>, and <td>. It's about good practices that can make your life easier and the browser work faster.

Avoiding potential disasters

Creating elements via string concatenation can be as appealing as pineapple on pizza! Use jQuery or createElement instead. Trust me, it's better:

var newRow = $('<tr>').addClass('newRowClass'); // Here's your row, bro!

Working with content manipulation

Injecting content into cells? Use .text() for plain text or .append() to add elements. It's like filling cupcakes without the mess:

$('td').eq(0).text('Safe Content'); // Do you feel safe? $('td').eq(1).append($('<span>').addClass('label').text('Label')); // Extra fancy label!

Creating table headers dynamically

Give table headers a dynamic spin with an array and jQuery magic:

var headers = ['Name', 'Age', 'Location']; // The trio of data truth var thead = $('<thead>'); var headerRow = $('<tr>'); $.each(headers, function(i, header) { headerRow.append($('<th>').text(header)); // Adding a crown of thorns... or headers! }); thead.append(headerRow); // Finally, a head for our table! table.prepend(thead);