I have a html which looks roughly like this:
<tr id="row">
<td id="cell_1">Cell 1</td>
<td id="cell_4">Cell 4</td>
<td id="cell_8">Cell 8</td>
<td id="cell_9">Cell 9</td>
<td id="cell_11">Cell 11</td>
...
</tr>
I have no way of changing it. For example, I have a variable cell, which points to the jQuery object representing the second td and I would like to get the element which is n cells after the cell. One way to get it would be:
var cell = $("#cell_4");
var next = cell;
for (var i = 0; i < n; i++) {
next = next.next();
}
But I think that wouldn’t be the most proper way since it requires n amount of “moves” through the DOM. The other way I could think off involves using the index() method (not tested so it could contain some errors but I think the method is understandable):
var index = $("#row > td").index(cell);
var next = $("row td:nth-child(" + index + n + ")");
Is there a “better”, built in, way to achieve that result? For example, something which would look like this:
var next = cell.nextTimes(n);
As the cells in questions have
idvalues, if you can derive the value of the one you want from where you’re starting, you can just use$('#cell_' + derivedValue).But if you can’t do that, you can use
nextAllandeq:nextAllreturns all of the element’s following (next) siblings, andeqreduces the matched set to the element at the given index.So for example,
cell.nextAll().eq(1)starting fromcell_1in your example would returncell_8(cell_4would becell.nextAll().eq(0)).Live example