How to select a range of elements in jQuery

JavascriptJquery

Javascript Problem Overview


<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.

Javascript Solutions


Solution 1 - Javascript

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)

Solution 2 - Javascript

Using the .slice() function does exactly what I need.

Solution 3 - Javascript

You should be able to do this by extracting a slice of the array thus. It's the line

$("div[id='myDiv'] > a").slice(1,4).css("background","yellow");

that you're interested in. It 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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnickfView Question on Stackoverflow
Solution 1 - JavascriptAlexander ProkofyevView Answer on Stackoverflow
Solution 2 - JavascriptnickfView Answer on Stackoverflow
Solution 3 - JavascriptpaxdiabloView Answer on Stackoverflow