user1170330 user1170330 - 6 months ago 23
HTML Question

Move td to new column

I have a table like that:

<table>
<tr>
<td>some column|1</td>
<td id="abc|1">abc</td>
</tr>
<tr>
<td>another column|1</td>
<td id="def|1">def</td>
</tr>
<tr>
<td>some column|2</td>
<td id="abc|2">abc</td>
</tr>
<tr>
<td>another column|2</td>
<td id="def|2">def</td>
</tr>
</table>


How can I move the
tds
with the suffix
|2
to the right, so adding a 3rd column? Also, the remaining "empty" td "some column|2" and "another column|2" should be removed completely.

The final result should look as follows:

enter image description here

This is the desired code:

<table>
<tr>
<td>some column|1</td>
<td id="abc|1">abc</td>
<td id="abc|2">abc</td>
</tr>
<tr>
<td>another column|1</td>
<td id="def|1">def</td>
<td id="def|2">def</td>
</tr>
</table>


This is my approach, which doesn't work:

$("table td:nth-child(2)[id$=2]").after("table td:nth-child(2)");


FIDDLE.

Answer

Use this code

var firstTd = $("table").find("tr:nth-child(3) > td:nth-child(2)");
var secondTd = $("table").find("tr:nth-child(4) > td:nth-child(2)");

$("table").find("tr:nth-child(3), tr:nth-child(4)").remove();
$("table").find("tr:nth-child(1)").append(firstTd);
$("table").find("tr:nth-child(2)").append(secondTd);
table, tr, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
  <tr>
    <td>some column|1</td>
    <td id="abc|1">abc</td>
  </tr>
  <tr>
    <td>another column|1</td>
    <td id="def|1">def</td>
  </tr>
  <tr>
    <td>some column|2</td>
    <td id="abc|2">abc</td>
  </tr>
  <tr>
    <td>another column|2</td>
    <td id="def|2">def</td>
  </tr>
</table>