1

This is my code.

<table>
    <tbody>
        <tr>
            <td>Some Data</td>
            <td>Some Data</td>
            <td>Some Data</td>
            <td>Some Data</td>
    </tr>           
    </tbody>
</table>

I want to add </tr><tr> in between the row programatically at runtime:

<table>
    <tbody>
        <tr>
            <td>Some Data</td>
            <td>Some Data</td>
    </tr>
    <tr>
            <td>Some Data</td>
            <td>Some Data</td>
    </tr>           
    </tbody>
</table>

I tried $('tr td').eq(1).after('</tr><tr>');, but it instead gave:

<table>
    <tbody>
        <tr>
            <td>Some Data</td>
            <td>Some Data</td>
        </tr/>
        <tr/>
            <td>Some Data</td>
            <td>Some Data</td>
        </tr>           
    </tbody>
</table>

So, how can I achieve the required functionality?

4 Answers 4

4

You need to split the row into two. You could do this using the following:

​$(function() {
    $('tbody tr').each(function() {  
        var cells = $(this).children('td'),
             row1 = $('<tr />'),
             row2 = $('<tr />');

        row1.append(cells[0]).append(cells[1]);
        row2.append(cells[2]).append(cells[3]);

        $(this).replaceWith(row1.add(row2));
    });​​​​​​​
});

Please see the sample jsFiddle here > http://jsfiddle.net/ayYa5/

Sign up to request clarification or add additional context in comments.

3 Comments

Hey buddy, your was good enough, but @Asad 's answer seems better performance-wise as well as to eyes... :)
Thanks. Just be cautious though, as his solution will only work for the first <tr> element.
Hey, yeah, but that isn't of much concern... :)
1

In terms of string manipulation, you are inserting "<tr></tr>".

In terms of DOM manipulation, however, you are making a new tr and moving two of the children of the original to it. If you use DOM manipulation tools, you have to follow the DOM manipulation logic.

$('tr').eq(0).after('<tr></tr>');
$($('tr td').eq(1).nextAll()).appendTo($('tr').eq(1));

Comments

0

I came up with this:

$('<tr></tr>').appendTo($('tbody'));
$('tbody tr:first-child td:last-child').appendTo($('tbody tr:last-child'));
$('tbody tr:first-child td:last-child').appendTo($('tbody tr:last-child'));

Live demo here

Comments

0

Well, it heavily depends on the format of data you have, but here's what you can try:

$( "td" ).unwrap( );

var wrap_tds = function( ) {
    var els = $( "tbody" ).children( "td:lt(2)" );
    if (els.length) {
        els.wrap( "tr" );
        wrap_tds( );
    }
};
wrap_tds( );

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.