Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to convert table to div's and append th in front of each td

I am trying to convert all tables to divs and add the th html or contents of the th in from of each td that is converted to a div.

So my table would look like this:

<table>
    <tr>
      <th>Title 1</th>
      <th>Title 2</th>
      <th>Title 3</th>
      <th>Title 4</th>
      <th>Title 5</th>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
      <td>Data 5</td>
    </tr>               
</table>

And I want to convert it so it is like this:

<div class="box">
<div class="row-fname"><span class="fname-label">TH Data</span> : <span class="fname-data">Data 1</span></div>
<div class="row-lname"><span class="lname-label">TH Data</span> : <span class="lname-data">Data 2</span></div>
<div class="row-address"><span class="address-label">TH Data</span> : <span class="address-data">Data 3</span></div>
<div class="row-city"><span class="city-label">TH Data</span> : <span class="city-data">Data 4</span></div>
<div class="row-state"><span class="state-label">TH Data</span> : <span class="state-data">Data 5</span></div>

I found this code that almost works but can figure out how to make it get the th if there are any th's and add them before each td's data span.

$('.content table').replaceWith(function() {
    var html = '';

    $('tr', this).each(function() {         
        html += '<div class="box grey-bg">';
        $('th, td', this).each(function() {
            html += '<span>' + $(this).html() + '</span>';
        });
        html += '</div>';
    });

    return '<div class="">' + html + '</div>';
});

Any help would be soooo greatly appreciated!!

like image 745
Aaron Avatar asked May 23 '12 21:05

Aaron


People also ask

How to append an element as a first child in jQuery?

The . prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).

How to add data to html table using jQuery?

This function uses the append() method to add a <tr> with the appropriate number of <td> tags to form a row for your table. Use a jQuery selector to locate the ID attribute of your table and the <tbody> tag, and append a <tr> and the <td> tags as shown in the following code snippet.

Can you wrap a TR in a div?

You should not be doing that... is not a valid HTMl markup... Rows can not be wraped by divs.

How do you traverse a table in jQuery?

The jQuery traversing methods allow you to iterate DOM elements in a DOM hierarchy. Use the selector to get the reference of an element(s) and then call jQuery traversing methods to edit it. Important DOM manipulation methods: each(), children(), find(), first(), parent(), next(), previous(), siblings() etc.


2 Answers

This works:

$('.content table').replaceWith(function() {

    var $th = $(this).find('th'); // get headers
    var th = $th.map(function() {
        return $(this).text();
    }).get(); // and their values

    $th.closest('tr').remove(); // then remove them

    var $d = $('<div>', { 'class': 'box' });

    $('tr', this).each(function(i, el) {
        var $div = $('<div>', {'class': 'inner'}).appendTo($d);
        $('td', this).each(function(j, el) {
            var n = j + 1;
            var $row = $('<div>', {
                'class': 'row-' + n
            });
            $row.append(
            $('<span>', {
                'class': 'label-' + n,
                text: th[j]
            }), ' : ', $('<span>', {
                'class': 'data-' + n,
                text: $(this).text()
            })).appendTo($div);
        });
    });

    return $d;
});

demo at http://jsfiddle.net/alnitak/UK395/

like image 174
Alnitak Avatar answered Oct 02 '22 20:10

Alnitak


Here is my improvisation :)

Add data-name tags to each <th> in order to distinguish the names of the fields:

<table>
    <tr>
        <th data-name="fname">Title 1</th>
        <th data-name="lname">Title 2</th>
        <th data-name="address">Title 3</th>
        <th data-name="city">Title 4</th>
        <th data-name="state">Title 5</th>
    </tr>
    <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
    </tr>               
</table>​

And try the code below. At least you will get exactly the structure you need.

$("table").replaceWith(function() {
    var block = $("<div />").addClass("box");
    $("tr:first th", this).each(function() {
        var name = $(this).data("name");
        var spanLabel = $("<span />").addClass(name + "-label").html(this.innerHTML);
        var spanData = $("<span />").addClass(name + "-data");
        $("<div />").addClass("row-" + name).append(spanLabel, " : ", spanData).appendTo(block);
    });
    $("tr:last td", this).each(function(index) {
        block.children("div:eq(" + index + ")").children(":last").html(this.innerHTML);
    });
    return block;
});

DEMO: http://jsfiddle.net/BsUVA/


UPDATE. If you unable to add extra data attributes to <th> tags, there is not a big problem. For not hardcoding, we can move the names to array (as follows) and use it instead.

var names = [
    "fname",
    "lname",
    "address",
    "city",
    "state"
];

DEMO: http://jsfiddle.net/BsUVA/1/

like image 36
VisioN Avatar answered Oct 02 '22 19:10

VisioN