Kacper G.
Kacper G.

Reputation: 692

JQuery - Select range of elements

I have got a problem. I need to select all elements which are after some element and before another element. Here is example:

<div>
    <span id="first"></span>
    <span id="second"></span>
    <span id="third"></span>
    <span id="fourth"></span>
    <span id="fifth"></span>
    <span id="sixth"></span>
    <span id="eight"></span>
</div>

And I want to get all elements from #second to, for example, #fifth. Maybe a function like $('div').children().selectRange(1, 4); exist, but what is the name of this? Thanks for help.

Upvotes: 0

Views: 1027

Answers (2)

amazedinc
amazedinc

Reputation: 418

Basically youre looking for the slice function:

$("div span" ).slice(2,5).remove();

In my example I am removing the items you wanted, but you can do whatever you need with them after you slice them.

Fiddle: https://jsfiddle.net/rtk4bosz/

If you want to work with the items use the following where each $(this) is the reference to the item you selected:

$("div span" ).slice(2,5).each(function(){
    alert($(this).text());
});

Fiddle: https://jsfiddle.net/pe5b814a/

Upvotes: 2

Pete
Pete

Reputation: 58412

Use .nextUntil()

$('#second').nextUntil('#sixth').css('color','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <span id="first">1</span>
    <span id="second">2</span>
    <span id="third">3</span>
    <span id="fourth">4</span>
    <span id="fifth">5</span>
    <span id="sixth">6</span>
    <span id="eight">8</span>
</div>

Upvotes: 3

Related Questions