html - More efficient way of recreating elements with JavaScript -
i have html table, each row clickable , acts accordion. when row clicked, few elements (another table, few other div elements, etc) visible underneath each row. here fiddle functionality:
http://jsfiddle.net/7dfwrje7/5/
the problem is, if had n number of rows, i'd have append code hidden elements each row in order work, is, code:
<tr> <td colspan="6"> <input id="row1" type="checkbox"> <table> <tr> <th>phone number</th> <td>555-3226</td> <th>city:</th> <td>new york</td> </tr> <tr> <th>hire date:</th> <td>8/13/12</td> <th>salary:</th> <td>$48,000</td> </tr> </table> </td> </tr>
in addition, have give input new id each time row generated:
<input id="row1" type="checkbox">
i have loop i've written in javascript of that. new table rows created in each iteration , have code manually creates each element html , appends each generated row:
<tr> <td colspan="6"> <input id="row1" type="checkbox"> <table> <tr> <th>phone number</th> <td>555-3226</td> <th>city:</th> <td>new york</td> </tr> <tr> <th>hire date:</th> <td>8/13/12</td> <th>salary:</th> <td>$48,000</td> </tr> </table> </td> </tr>
so within loop creating rows, have like:
var createrow = document.createelement("tr"); var createcell = docment.createelement("td"); tbody.appendchild(createrow); tbody.appendchild(createcell); etc.....
and have html create way, there 100-200 lines of javascript code creating elements. of working me, question: there better , more efficient way of doing this, instead of recreating every single html element in javascript code? both, efficient in terms of writing less code of , efficient in terms of performance? i'm trying stick pure javascript, no libraries. suggestions appreciated.
from jsfiddle, understand implemented accordion opening functionality strange trick: label covers entire row, css pseudo class on corresponding input reveal table.
this fun because not involve script, requires creating more elements , using unique id's per input (hence problem of having assign unique id's). prevents copying row text, , still have line on hidden row (which row height 0 because empty). finally, nested table must created.
since anyway need scripting generate main table, why not using event listening on table rows perform this? generate nested table on demand (when user clicks on row), not have create them @ table initialization. saves time on main table processing.
as generating main table, refer this comparison performance. shows 2 fastest methods:
- generating string of html code, filling
element.innerhtml
@ end. - using generated element (or document fragment, or cloned node) outside dom, filling other elements needed, inserting in dom @ end.
demo: http://jsfiddle.net/7dfwrje7/7/ (i used html string method)
Comments
Post a Comment