How could I go about converting an HTML table (I will provide code below) into
It does seem like a crazy thing to have to do. I just wrote a jQuery plugin to do this though. Working with an old web app where we don't want to really dig into the backend code and are on a limited budget. So, just taking the data that is dumped out in tables, converting them to divs, so I can float them around, style them up and make the data look better.
The system is rending data that is not really 'tabular' data.
https://github.com/ryandoom/jquery-plugin-table-to-div
If anyone is interested in the future.
Long story short, I am using a PHP script that outputs contents into an HTML table and it has proven very difficult to edit the PHP and convert the table elements into 's.
Using tables for non-tabular contents is frowned upon. However, if you've already served content in a table, and it looks well, you should not use jQuery to turn the table in divs, just to get rid off the table.
If you still want to use jQuery to turn the table in a div, you have to consider the structure of the <div>
elements. Then, loop through each table row, loop through each table cell, and move the contents to a newly created <div>
. At the end, replace the table with the set of <div>
s.
No need to loop through the elements and copy the attributes, just pull the table contents as a string and run a simple string replace ...
$('table').replaceWith( $('table').html()
.replace(/<tbody/gi, "<div id='table'")
.replace(/<tr/gi, "<div")
.replace(/<\/tr>/gi, "</div>")
.replace(/<td/gi, "<span")
.replace(/<\/td>/gi, "</span>")
.replace(/<\/tbody/gi, "<\/div")
);
... or, if you want an unordered list ...
$('table').replaceWith( $('table').html()
.replace(/<tbody/gi, "<ul id='table'")
.replace(/<tr/gi, "<li")
.replace(/<\/tr>/gi, "</li>")
.replace(/<td/gi, "<span")
.replace(/<\/td>/gi, "</span>")
.replace(/<\/tbody/gi, "<\/ul")
);
This will also retain your classes and attributes.
Perhaps the best solution isn't jQuery related, but PHP ... you could use PHP's str_replace()
to do the same thing, only before outputting from PHP?
$table_str = //table string here
$UL_str = str_replace('<tbody', '<ul id="table"', $table_str);
$UL_str = str_replace('<tr', '<li', $UL_str);
$UL_str = str_replace('</tr', '</li', $UL_str);
$UL_str = str_replace('<td', '<span', $UL_str);
$UL_str = str_replace('</td', '</span', $UL_str);
$UL_str = str_replace('</tbody', '</ul"', $UL_str);