Convert a description list to a table
A fiddle for a work project.
by bizamajig
HTML
<h1>Convert a description list to a table</h1>
<p>A real use of this on a production website would, of course, only display either a table or the list. I'm showing both for the example.</p>
<div id="table-receiver" class="container"></div>
<div id="table-transformer" class="container">
<dl>
<dt>First Name</dt>
<dd>Ashley</dd>
<dt>Last Name</dt>
<dd>Coulson</dd>
<dt>Title</dt>
<dd>Violinist</dd>
<dt>Birthdate</dt>
<dd>2006-06-14</dd>
</dl>
<dl>
<dt>First Name</dt>
<dd>David</dd>
<dt>Last Name</dt>
<dd>Coulson</dd>
<dt>Title</dt>
<dd>Warrior</dd>
<dt>Birthdate</dt>
<dd>2007-10-28</dd>
</dl>
<dl>
<dt>First Name</dt>
<dd>Sam</dd>
<dt>Last Name</dt>
<dd>Coulson</dd>
<dt>Title</dt>
<dd>Prophet</dd>
<dt>Birthdate</dt>
<dd>2013-02-11</dd>
</dl>
</div>
CSS
div#table-receiver table {
border-collapse: collapse;
border: 3px double #ccc;
}
div#table-receiver table td,
div#table-receiver table th {
border: 1px solid #ccc;
padding: 0.3em;
}
dl {
border: 3px double #ccc;
padding: 0.3em;
}
dt {
float: left;
clear: left;
width: 100px;
text-align: right;
font-weight: bold;
color: green;
}
dt:after {
content: ":";
}
dd {
margin: 0 0 0 110px;
padding: 0 0 0.5em 0;
}
JavaScript
// Setup.
var tableParts = {
tableSource: "div#table-transformer",
tableContainer: "div#table-receiver",
tableHtml: "<table><thead><tr></tr></thead><tbody></tbody></table>",
descriptionList: "div#table-transformer dl",
headerRow: "div#table-receiver thead tr",
tableBody: "div#table-receiver table tbody"
};
// Create the table.
$(tableParts.tableContainer).html(tableParts.tableHtml);
// Array of DL.
var tableDL = [];
tableDL = $(tableParts.descriptionList).toArray();
// Get array of DL[0] DT.
var tableColumnText = $("dt", tableDL[0]).toArray();
// Make an object of the table header row.
var tableHeaderRow = $(tableParts.headerRow);
$.each($(tableColumnText), function(index, value) {
$(tableHeaderRow).append("<th>" + $(tableColumnText[index]).html() + "</th>");
});
// Make an object of the table body.
var tableBody = $(tableParts.tableBody);
// For each dd in the dl, get the html.
$.each($(tableDL), function(index, value) {
var tableDD = $("dd", this).toArray();
var tableDDText;
$.each($(tableDD), function(index, value) {
tableDDText += "<td>" + $(tableDD[index]).html() + "</td>";
});
$(tableBody).append("<tr>" + tableDDText + "</tr>");
});