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


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

    $(document).ready(function(){
    var headers = new Array();
    var values = new Array();
       $('table th').each(function(){
                headers.push($(this).text());

        });

       $('table td').each(function(){
                values.push($(this).text());

        });

     var returndata = "<ul>";
         for(i=0;i<headers.length;i++){
           returndata+="<li>"+headers[i]+"<p>"+values[i]+"</p></li>";
        }

    returndata+="</ul>"; 


 $("table").html(returndata);   


    });

<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>

<button onclick="convert()">convert</button>


<script language="javascript">
    function convert() {
        var a = document.getElementsByTagName('th');
        var c = document.getElementsByTagName('td');
        var b = '';
        var d = '';
        for (var i=0;i< a.length;i++) {
            b += "<li>" + a[i].innerHTML + "</li>";
        }
        a[0].parentNode.innerHTML=b;
        for (var i=0;i< c.length;i++) {
            d += "<p>" + c[i].innerHTML + "</p>";
        }
        c[0].parentNode.innerHTML=d;
    }

</script>

With Plain Javascript

jsfiddle

链接地址: http://www.djcxy.com/p/17242.html

上一篇: 从盒子中获取每个价值

下一篇: 如何将表格转换成li和td到javascript中使用<p>?