Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a range of elements in jQuery

<div id="myDiv">      <a>...</a>      <a>...</a>      <a>...</a>      <a>...</a>      <a>...</a>      <a>...</a> </div> 

If you wanted to select the 2nd, 3rd and 4th a tags in the above example, how would you do that? The only thing I can think of is:

$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)") 

But that doesn't look to be very efficient or pretty. I guess you could also select ALL the as and then do run .each over them, but that could get very inefficient if there were a lot more as.

like image 284
nickf Avatar asked Oct 09 '08 04:10

nickf


People also ask

What is the syntax used to collect a group of elements in jQuery?

var divs = $( "div" );

What is selection range?

The basic concept of selection is Range, that is essentially a pair of “boundary points”: range start and range end. A Range object is created without parameters: let range = new Range(); Then we can set the selection boundaries using range.


1 Answers

jQuery slice() function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself.

In your particular case you should use

$("#myDiv a").slice(1, 4) 
like image 156
Alexander Prokofyev Avatar answered Oct 07 '22 08:10

Alexander Prokofyev