Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HTML table to ul li using jquery

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.

like image 393
Miuranga Avatar asked Feb 12 '13 09:02

Miuranga


2 Answers

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/

like image 188
Viktor S. Avatar answered Nov 10 '22 14:11

Viktor S.


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

like image 6
Dipesh Parmar Avatar answered Nov 10 '22 14:11

Dipesh Parmar