:gt
supports negative indices
negative index: Zero-based index, counting backwards from the last element.
var xTrs = $('tr');
var xLastTrs = xTrs.filter(':gt(-5)');
so does slice
var xLastTrs = xTrs.slice(-5);
Domanda
Consider that, i had selected all tr
elements from a table
which contains 10 rows, now from that i just tried to filter out the last 5 elements by using the following way
var xTrs = $('tr');
var xLastTrs = xTrs.filter(':gt('+ (xTrs.length - 6) +')');
Now the above snippet is working fine when i am having more than 5 rows in that table, but when the scenario becomes like, the table is having only 5 rows, the selector get validated as xTrs.filter(':gt(-1)');
and it is refusing to fetch the expected result.
what i am doing wrong here..? I thought :gt(-1)
would select all the elements which is having index from 0 to 4 in that context. Please correct me if i am thinking in a wrong way.
And by the way, first tell me how can we achieve that by using :gt()
and after that let me know some other efficient ways.
Soluzione
:gt
supports negative indices
negative index: Zero-based index, counting backwards from the last element.
var xTrs = $('tr');
var xLastTrs = xTrs.filter(':gt(-5)');
so does slice
var xLastTrs = xTrs.slice(-5);
Altri suggerimenti
Test if xTrs.length
is more than 5
before filtering:
xLastTrs = (xTrs.length <= 5) ? xTrs ? xTrs.filter(':gt('+ (xTrs.length - 6) +')');
Try,
var xTrs = $('tr');
var xLen = xTrs.length - 5;
var xLastTrs = xTrs.filter(':eq('+ xLen +'),:gt(' + xLen + ')');
Clever isn't.?