I have a complex HTML table with horizontal and vertical headings looking like this.
The HTML code is simple:
<table>
<tr>
<th>(empty)</th>
<th>Heading 1</th>
<th>Heading 2</th>
</tr>
<tr>
<th>Heading A</th>
<td>content for 1 and A</td>
<td>content for 2 and A</td>
</tr>
<tr>
<th>Heading B</th>
<td>content for 1 and B</td>
<td>content for 2 and B</td>
</tr>
<tr>
<th>Heading C</th>
<td>content for 1 and C</td>
<td>content for 2 and C</td>
</tr>
</table>
Now, I want to give the users of my website the possibility to swap the content of the table. I.e.: change the horizontal and vertical order, so that afterwards the vertical headings are horizontal, the horizontal headings are vertical and the table cells accordingly. Sounds complicated, but you will get it by looking at the picture:
The HTML would be now:
<table>
<tr>
<th>(empty)</th>
<th>Heading A</th>
<th>Heading B</th>
<th>Heading C</th>
</tr>
<tr>
<th>Heading 1</th>
<td>content for 1 and A</td>
<td>content for 1 and B</td>
<td>content for 1 and C</td>
</tr>
<tr>
<th>Heading 2</th>
<td>content for 2 and A</td>
<td>content for 2 and B</td>
<td>content for 2 and C</td>
</tr>
</table>
Technically speaking, evey table cell (th
and td
) has to swap its indices: The column index should become the row index and the column index should become the rown index. But how do I do that using JavaScript and or JQuery?
I already found out how to get the row and column index:
//column
$(this).parent().children().index(this);
//row
$(this).parent().parent().children().index(this.parentNode);
But there seems no JQuery function for "set table cell position", there is just .inserAfter
and honestly, I don't know how to cope with that.