chalist chalist - 1 month ago 10
jQuery Question

Many table sorting with first td

I have many tables:

<table id="342">
<tr>
<td>342</td>
<td>test</td>
</tr>
</table>
<table id="533">
<tr>
<td>533</td>
<td>test</td>
</tr>
</table>
<table id="156">
<tr>
<td>156</td>
<td>test</td>
</tr>
</table>


Can I sort these tables with first td jquery from 1 to ... ?

Answer

Try this:

HTML:

<div id="test">
<table id="342">
  <tr>
     <td>342</td>
     <td>test</td>
  </tr>
</table>
<table id="533">
  <tr>
     <td>533</td>
     <td>test</td>
  </tr>
</table>
<table id="156">
  <tr>
     <td>156</td>
     <td>test</td>
  </tr>
</table>
</div>

jQuery:

var tables = $('table');

tables.sort(function(a, b) {
    return parseInt($('tr td:first', a).html()) > parseInt($('tr td:first', b).html())
});
$('div#test').empty().append(tables);

DEMO

Comments