I want to convert HTML
table to ul
and li
elements. my table structure is
<table>
<tbody>
<tr>
<th>1974</th>
<td>UK</td>
</tr>
<tr>
<th>1976</th>
<td>Street</td>
</tr>
<tr>
<th>1976-2002</th>
<td>visitors.</td>
</tr>
</tbody>
</table>
I tried to convert this to
<ul>
<li>
<p>1974</p>
<p>UK</p>
</li>
<li>
<p>1976</p>
<p>Street</p>
</li>
<li>
<p>1976-2002</p>
<p>visitors.</p>
</li>
</ul>
using jquery
replaceWith
function as below. Here I firstly going to convert <tbody>
element.
$(document).ready(function() {
$("tbody").each(function(){
var html = $(this).html();
$(this).replaceWith("<ul>" + html + "</ul>");
});
)};
but this not give any positive answer. Anybody have any idea how to do this.
Thanks.
I would do it like this:
$(document).ready(function() {
var ul = $("<ul>");
$("table tr").each(function(){
var li = $("<li>")
$("th, td", this).each(function(){
var p = $("<p>").html(this.innerHTML);
li.append(p);
});
ul.append(li);
})
$("table").replaceWith(ul);
});
UL first is created, and than table is replaced with UL.
Demo: http://jsfiddle.net/yXyCk/
Try
$('table').replaceWith( $('table').html()
.replace(/<tbody/gi, "<ul id='table'")
.replace(/<tr/gi, "<li")
.replace(/<\/tr>/gi, "</li>")
.replace(/<td/gi, "<p")
.replace(/<\/td>/gi, "</p>")
.replace(/<th/gi, "<p")
.replace(/<\/th>/gi, "</p>")
.replace(/<\/tbody/gi, "<\/ul")
);
Above code is tested and worked for me..
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With