Mounir Federere Mounir Federere - 7 months ago 12
Javascript Question

How to wrap every 3rd <td> with a <tr> using jQuery?

I am trying to wrap

<tr>
tags around every 3rd
<td>
. Is there a way to do so?

Html

<table id="tblOne">
<tbody>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</tbody>
</table>


I want the output to be something like this:

<table id="tblOne">
<tbody>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</tbody>
</table>

Answer
var td = $("#tblOne td");                    // Getting all td
td.each(function(i){                         // Looping the td 
    if (i % 3 == 0) {                        // Splitting td as multiple of 3
        td.slice(i, i+3).wrapAll('<tr/>')    // Wrapping it inside tr
    }
}).parent('tr').unwrap();                    // Remove parent tr

Working Demo

Comments