Tag Archive for: order
Sort by table content
/in HTML5, JavaScript/by GénesisHow can you sort any HTML table using jQuery?
Element 40 | ✔ |
Element 2 | ✔ |
Element 29 | ✔ |
Element 28 | ✔ |
Element 5 | ✔ |
Suppose you only want to use the number.
- First we must sort elements
- After that we have to keep going deleting each element and appending again to the table with the new order
// JS $("table tr").sort(function (a, b) { var a_num = $(a).children(":first-child").text().split(" ")[1]; var b_num = $(b).children(":first-child").text().split(" ")[1]; return parseInt(a_num) - parseInt(b_num); }).each(function(){ var elem = $(this); elem.remove(); $(elem).appendTo("table > tbody"); });
See a real example:
Edited: improved and without jQuery.