Mounir Federere Mounir Federere - 7 months ago 8
Javascript Question

How to insert a <tr> after every 3rd <td> using jQuery?

I am trying to insert

<tr>
tags after each 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></tr>
</tr>
</tbody>
</table>

Answer
var td = $("#tblOne td");
td.each(function(i){
    if (i % 3 == 0) {
        td.slice(i, i+3).wrapAll('<tr/>')
    }
}).parent('tr').unwrap();

Working Demo

Comments