Ryan Barnaby
Ryan Barnaby

Reputation: 169

Split multiple data cells per row <td> in single data cell per row - jQuery

I have a table with multiple data cells per row, like this:

<table>
    <tbody>
        <tr>
            <td>content 1</td>
            <td>content 2</td>
            <td>content 3</td>
        </tr>
        <tr>
            <td colspan="2">content 4</td>
            <td>content 5</td>
        </tr>
        <tr>
            <td colspan="3">content 6</td>
        </tr>
    </tbody>
</table>

How can I split all elements in independent rows using jQuery. To be be more specific the result will have to be like this

<table>
    <tbody>
        <tr>
            <td>content 1</td>
        </tr>
        <tr>
            <td>content 2</td>
        </tr>
        <tr>
            <td>content 3</td>
        </tr>
        <tr>
            <td>content 4</td>
        </tr>
        <tr>
            <td>content 5</td>
        </tr>
        <tr>
            <td>content 6</td>
        </tr>
    </tbody>
</table>

Upvotes: 1

Views: 1500

Answers (5)

Sanjeevi Rajagopalan
Sanjeevi Rajagopalan

Reputation: 232

Check out this fiddle

var $newRows = '';
$('td').each(function (thisTd, index) {
    $newRows += '<tr><td>' + $(this).text() + '</td></tr>';
});
$('#t-body').html($newRows);

Upvotes: 0

SarathSprakash
SarathSprakash

Reputation: 4624

Working DEMO

Try this

$(document).ready(function () {
    var child;
    $("td").each(function () {
        $(this).removeAttr('colspan');
        child+="<tr>"+$(this)[0].outerHTML+"</tr>";
    });
    $('tbody').html(child);
});

Hope this helps,Thank you

Upvotes: 0

Greenhorn
Greenhorn

Reputation: 1700

Try this:

$("table tr").find("td").each(function(){
$("table tbody").append("<tr><td>"+$(this).text()+"</td></tr>");
    $(this).parent().remove();
})

Working Fiddle

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var $tbody = $('tbody'), $tds = $tbody.find('td:not(:first)').detach();
$tbody.find('tr:not(:has(td))').remove()
$tds.removeAttr('colspan').wrap('<tr />').parent().appendTo('tbody');

Demo: Fiddle

Upvotes: 0

Skyline0705
Skyline0705

Reputation: 11

var new_trs="";
$('td').each(function(){
    new_trs += "<tr><td>"+this.innerHTML"</td></tr>";

});$('tbody').html(new_trs);

Upvotes: 0

Related Questions