I have a scenario where I receive the data from JSON, and that data should be dynamically displayed across the web page, in complex HTML structures (ie tables containing lists etc).
Any time the JSON data is received, I want my HTML elements to be dynamically regenerated. For example, HTML table rows count will depend on the data from JSON.
Given that the HTML structures are complex, and they should also have some CSS associated to them - what is the best way to do that?
My idea was to "declare" single elements in the HTML file, and then putting them all together into a complex structure in Javascript (jQuery).
For example, if I need to generate a table that has a list in each cell, and every list is dynamically created and filled with elements in javascript, I would then declare the following:
HTML file snippet with declarations
<!-- Define table -->
<script type="text" id="my_table">
<table class="a-bordered a-align-center a-spacing-base a-size-base"></table>
</script>
<!-- Define table heading element: each column has it's own heading -->
<script type="text" id="my_table_heading">
<th class="a-color-base a-size-base a-text-center"></th>
</script>
<!-- Define table row -->
<script type="text" id="my_table_row">
<tr class="a-spacing-base a-spacing-top-base a-text-center"></tr>
</script>
<!-- Define list -->
<script type="text" id="my_list">
<ol class="a-ordered-list a-vertical a-spacing-base"></ol>
</script>
<!-- Define list item -->
<script type="text" id="my_list_item">
<li class="a-list-normal a-spacing-none a-spacing-top-mini"><span class="a-list-item a-color-link"></li>
</script>
When I have all that declared, I would use it in jQuery to dynamically create my table with the elements predefined in HTML. Something like the following..
Javascript file snippet
// get the predefined table heading
var table_heading = $($("#my_table_heading").html());
// append it to the table :: do that in a for loop for all headings
$("#my_table").append(table_heading);
// get the predefined list from HTML
var list = $($("#my_list").html());
// append it to the cell
$("#my_cell").append(list);
My question is that the right approach? I am new to Javascript/jQuery/HTML, so I would like to know the best practice how to generate complex html structures in it?
- Is this OK?
- Is there any framework that does it better?