thowzif thowzif - 1 month ago 4
HTML Question

Sorting <td> by id?

I am trying to sort the td tag in a table by it ids.
I have the Below code

<table>
<tr>
<th id="dv_8">COMPANY NAME</th>
<th id="dv_6">CONTACT 1</th>
<th id="dv_1">CONTACT 2</th>
<th id="dv_3">CONTACT 3</th>
<th id="dv_2">FAX</th>
<th id="dv_9">WILAYAT</th>
<th id="dv_5">CUSTOMER SEGMENT</th>
<th id="dv_10">FLCODE</th>
<th id="dv_7">Date Added</th>
<th id="dv_4">QNR Status</th>
</tr>




I want the sort the so that the output is

<table>
<tr>
<th id="dv_1">CONTACT 2</th>
<th id="dv_2">FAX</th>
<th id="dv_3">CONTACT 3</th>
<th id="dv_4">QNR Status</th>
<th id="dv_5">CUSTOMER SEGMENT</th>
<th id="dv_6">CONTACT 1</th>
<th id="dv_7">Date Added</th>
<th id="dv_8">COMPANY NAME</th>
<th id="dv_9">WILAYAT</th>
<th id="dv_10">FLCODE</th>
</tr>




What am I missing here ?

Answer

In plain JavaScript you may do it with:

Array.prototype.slice.call(document.getElementsByTagName('th')).sort(function(a, b) {
    return a.id.replace('dv_', '') - b.id.replace('dv_', '');
}).forEach(function(e) {
    e.parentNode.appendChild(e);
});

Or if you use jQuery:

$('table th').get().sort(function(a, b) {
    return a.id.replace('dv_', '') - b.id.replace('dv_', '');
}).forEach(function(e) {
    e.parentNode.appendChild(e);
});

DEMO: http://jsfiddle.net/b4Ngj/