Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using next() x number of times with jQuery

What's an easy way to iterate x number of times using next() (applying the same function each time)?

I am working in Sharepoint and have limited control of the HTML; what I can do is find an element by its ID, track down the closest <td>, hide() it, and then move on to the next one (I don't want all the <td>'s, just about 7 or 8 in a row).

The code below works but it's not that pretty.

$("#my-easily-identifiable-id").closest("td").hide();
$("#my-easily-identifiable-id").closest("td").next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().next().hide();
[ ... etc ... ]

What's a better way to do this?

Thanks

PS: added a fiddle (genius)

like image 485
thornomad Avatar asked Oct 07 '11 19:10

thornomad


3 Answers

Use .nextAll() + .andSelf() with .slice().

$("#my-easily-identifiable-id").closest("td").nextAll().andSelf().slice(0, 7);
like image 142
Matt Ball Avatar answered Nov 03 '22 23:11

Matt Ball


I think a simpler solution than those posted so far would be .nextUntil():

//to get next 8 elements
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+8) + ')');

//to get self and next 3
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+3) + ')').andSelf();

Grabs all "next" elements until the filter is hit (in this case we choose the next 8 elements). Verified by jsFiddle.

like image 30
Chad Avatar answered Nov 04 '22 00:11

Chad


I've not tried it, but perhaps the following might work (I'll test momentarily):

$("#my-easily-identifiable-id").siblings().slice($(this).index(),($(this).index() + 8)).hide();

Tested and verified with a JS Fiddle demo.

like image 1
David Thomas Avatar answered Nov 03 '22 23:11

David Thomas