2

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>
3
  • Don't have an answer for you, but I am curious why you would do this? Commented Feb 23, 2009 at 13:53
  • Yeah, this seems like an odd thing to do. Can you explain your context? Does StackOverflow post some random pointless questions to get page views up? Commented Feb 24, 2009 at 1:22
  • Plenty of reasons why someone would want to do this -- e.g., in mobile view, you might want the contents of the table to populate a dropdown menu. I know this is supposed to be a tough crowd, but no one can foresee every possible coding scenario, no matter how high your SO reputation. Commented Mar 2, 2015 at 18:45

4 Answers 4

11
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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like this better than @cletus' answer as it doesn't presume how many <td> -> <p> conversions to do.
2

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

Comments

0

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>

Comments

-1

I can see this being useful in SharePoint which likes to use a bunch of nested tables to render a simple list which is more efficient using ,

  • ...

  • Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.