views:

684

answers:

4

How would I transform a table

<table>
    <tr>
        <td>Name</td>
        <td>Price</td>
    </tr>
    <tr>
        <td>Name</td>
        <td>Price</td>
    </tr>  
</table>

to a list of paragraphs with jQuery

<ul>
    <li>
        <p>Name</p>
        <p>Price</p>
    </li>
    <li>
        <p>Name</p>
        <p>Price</p>
    </li>  
</ul>

<p><a id="products-show-list">Toggle list view</a></p>

<script type="text/javascript">
    $("#products-show-list").click(function(){...});
</script>
+2  A: 

You could try:

function convertToList() {
  var list = $("<ul></ul>");
  $("table tr").each(function() {
    var children = $(this).children();
    list.append("<li><p>" + children[0].text() + "</p><p>" + children[1] + "</p></li>");
  }
  $("table").replaceWith(list);
}
cletus
+4  A: 
function convertToList(element) {
    var list = $("<ul/>");

    $(element).find("tr").each(function() {
        var p = $(this).children().map(function() {
            return "<p>" + $(this).html() + "</p>";
        });

        list.append("<li>" + $.makeArray(p).join("") + "</li>");
    });

    $(element).replaceWith(list);
}
Alex Barrett
I like this better than @cletus' answer as it doesn't presume how many <td> -> <p> conversions to do.
Crescent Fresh
A: 
A: 

This still has some work left, but this is what I got to work so far:

<script>
$(function(){
 t2l("uglytable");
});

function t2l(divname)
{ 
 var ulist  = $("<ul></ul>");
 var table  = "div." + divname + " table";
 var tr   = "div." + divname + " table tr";

 $(tr).each(function(){
  var child = $(this).children();
  ulist.append("<li>" + child.text() + "</li>");
 });
 $(table).replaceWith(ulist);
}

</script>

<div class="uglytable">
  <table border="1">
   <tr>
    <td>lakers</td>
   </tr>
   <tr>
    <td>dodgers</td>
   </tr>
   <tr>
    <td>angels</td>
   </tr>
   <tr>
    <td>chargers</td>
   </tr>
  </table>
 </div>