tags:

views:

17

answers:

1

We have a table:

<table>
<tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
</tr>
</table>

We update this table by throwing into each <tr> only 3 <td>.

It must look like:

<table>
<tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
</tr>
<tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
</tr>
<tr>
    <td>7</td>
    <td>8</td>
    <td>9</td>
</tr>
<tr>
    <td>10</td>
</tr>
</table>

How can we do this?

Thanks.

+2  A: 

You can do it using .unwrap(), .slice(), and .wrapAll(), like this:

var elems = $("table tr td").unwrap();
for(var i = 0; i < elems.length; i+=3) {
  elems.slice(i, i+3).wrapAll("<tr></tr>");
}​

You can view a quick demo here, this takes the <td> elements, removes the surrounding <tr></tr>, groups them in sets of 3 and re-wraps those groups in <tr></tr>.

Nick Craver