Initially, you could sort the table with a basic sort
function (if the rows haven't been sorted already):
Markup
(Note: Added your custom val
attribute as a data attribute)
<table>
<tbody>
<tr data-val="1"><td>1st</td></tr>
<tr data-val="4"><td>3rd</td></tr>
<tr data-val="7"><td>4th</td></tr>
<tr data-val="2"><td>2nd</td></tr>
</tbody>
</table>
jQuery
$('table').html(function() {
return $(this).find('tr').sort(function(a, b) {
return $(a).data('val') > $(b).data('val');
});
});
Once the rows have been sorted, you can easily find the position to insert the new row by grabbing the first row where its data-val
is greater or equal to the data-val
of the newRow
:
var $newRow = $('<tr data-val="3"><td>Between 2nd and 3rd!</td></tr>');
var elementToInsertBefore = $('tr').filter(function() {
return $(this).data('val') >= $newRow.data('val');
}).get(0);
if (typeof elementToInsertBefore === 'undefined') {
$('table').append($newRow);
} else {
$newRow.insertBefore(elementToInsertBefore);
}
So, if the filter doesn't return an elementToInsertBefore
(ie. there were no existing rows with a data-val
greater, or equal to the $newRow's
data-val
, append it to the end of the table, otherwise insert it before the elementToInsertBefore
.
Side Note: It'd probably be more efficient to use a for
loop to get the elementToInsertBefore
. That way, as soon as you find a row which meets the criteria, you can break
out, which prevents further unecessary iterations (which could have a decent performance gain when dealing with a large number of rows).
If you want something more elaborate, have a look at the jQuery plugins mentioned.