Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert table th into li and td into <p> with javascript?

Hello I have table like this

<table>
  <tbody>
    <tr>
      <th>PROVINSI</th>
      <th>KABKOT</th>
      <th>KECAMATAN</th>
      <th>DESA</th>
    </tr>

    <tr>
      <td>KALIMANTAN TENGAH</td>
      <td>SERUYAN</td>
      <td>SERUYAN HILIR</td>
      <td>TANJUNG RANGAS</td>
    </tr>
  </tbody>
</table>

I want to convert this table into unordered list like this

<ul>
      <li>PROVINSI<p>KALIMANTAN TENGAH</p></li>
      <li>KABKOT<p>SERUYAN</p></li>
      <li>KECAMATAN<p>SERUYAN HILIR</p></li>
      <li>DESA<p>TANJUNG RANGAS</p></li>

</ul>

how can i do this with javascript?

i've tried this

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);   
}

but i don't really understand how to loop over this table. sorry

like image 352
Joan Natalie Avatar asked Nov 13 '13 11:11

Joan Natalie


1 Answers

Assuming that <table id="target">...</table>

JSFiddle

var ul = $("<ul>");
$("#target th").each(function(i, v){
  var li = $("<li>")
  li.append($(v).text());
  var p = $('<p>').append($($("#target td")[i]).text());
  li.append(p);
  ul.append(li);
})    
$("#target").replaceWith(ul);
like image 177
shyam Avatar answered Oct 21 '22 11:10

shyam