Sirisha Ancha Team : Web Development Tags : Web Development Tips & Tricks jQuery

JQuery - Dynamically create nested HTML elements

Sirisha Ancha Team : Web Development Tags : Web Development Tips & Tricks jQuery

JQuery Script

To start we need to get the our test table and empty the contents as shown below:

 var table = $("#TestTable");
 table.find('tbody').empty(); //Empty the contents before populating again

Here is one way to build up the tables contents, using the concatenated string method:

for(var i = 0; i < products.length; i++){
   var row = '<tr>';
   row = row + '<td>' + products[i].Id+ '</td>';
   row = row + '<td>' + products[i].Name+ '</td>';    
....          
   row = row + '<td>' + products[i].Status + '</td>';
   row = row + '</tr>';
   table.find('tbody').append(row);
}

But there are few drawbacks of writing such code:

  1. There is a need to keep a track of all the closing tags.
  2. The more complex the logic, the messier and less maintainable the code becomes.

So here is a more elegant way of writing the same code, where each HTML tag is added separately to its parent element. To make it simple, start with the lowest node and move upwards building its parent recursively.

Lets consider a list of objects, say "Products", that need to be populate our table on the fly. Each of the Product object maps to a row in a HTML table:

for(var i = 0; i < products.length; i++){                
    var row =  $('<tr/>', {class: '' }); 
    row.append($('<td/>').append(products[i].Id));
    row.append($('<td/>').append(products[i].Name));
....
    row.append($('<td/>').append(products[i].Status));
    table.find('tbody').append(row);
}

The above is only a simple example. There could be much more complex HTML tags that could be added in similar way.