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 want to select tags 2, 3 and 4 a in the above example, how do you do it? The only thing I can think of:
$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)") But it does not look very effective or beautiful. I think you could also select ALL a and then execute .each on it, but this can become very inefficient if there was a lot more than a s.
+49
nickf Oct 09 '08 at 4:53 2008-10-09 04:53
source share3 answers
The jQuery slice () function, which uses the indices of the first and last required elements, selects a subset of the matched elements. Please note that it does not include the last item.
In your particular case you should use
$("#myDiv a").slice(1, 4) +105
Alexander Prokofyev 09 Oct '08 at 5:32 2008-10-09 05:32
source shareUse . The slice () function does exactly what I need.
+9
nickf Oct 09 '08 at 5:06 2008-10-09 05:06
source shareYou must do this by extracting a slice of the array in this way. This is a string
$("div[id='myDiv'] > a").slice(1,4).css("background","yellow"); which interests you. This will affect the 2nd, 3rd and 4th elements.
<html> <head> <script type="text/javascript" src="jquery-1.2.6.pack.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(event){ $("div[id='myDiv'] > a").slice(1,4).css("background","yellow"); event.preventDefault(); }); }); </script> </head> <body> <div id="myDiv"> <a>1</a> <a>2</a> <a>3</a> <a>4</a> <a>5</a> <a>6</a> </div> <hr> <a href="" >Click here</a> <hr> </body> </html> +1
paxdiablo Oct 09 '08 at 5:40 2008-10-09 05:40
source share