Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get siblings between 2 elements

Tags:

jquery

How can I get the elements between 2 other elements?

Like if I had:

<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
<div class="c4"></div>
<div class="c5"></div>
<div class="c6"></div>
<div class="c7"></div>

I want to get the elements between div.c3 and div.c6.

like image 551
Francisc Avatar asked Jul 25 '11 13:07

Francisc


People also ask

What is a sibling element?

A sibling is an element that shares the same parent with another element. In the diagram below, the <li>'s are siblings as they all share the same parent - the <ul>.

Which of the following selector is used to select siblings?

The ("element ~ siblings") selector selects sibling elements that appear after the specified "element".

What is jQuery siblings?

jQuery siblings() Method Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward and backwards along siblings of DOM elements. Tip: Use the prev() or next() method to narrow down the search for only previous or next sibling elements.


2 Answers

With nextUntil [docs]:

var $siblings = $('.c3').nextUntil('.c6');
like image 93
Felix Kling Avatar answered Sep 21 '22 17:09

Felix Kling


You might want to first check if elements come in the proper order, othenwise nextUntil will return unexpected set of elements.

/**
 * Returns an array of sibling elements between `from` and `to` including `from` and `to`
 */
function getElementsInBetween (from, to) {
        var range = [];

        if (from.index() > to.index()) { //ensure that 'from' is before 'to'
            from = [to, to = from][0]; //swapping from and to
        }

        if (from.is(to)) {
            range = [from];
        } else {
            range = from.nextUntil(to).add(from).add(to);
            range = $.makeArray(range);
        }

        return range;
    };
like image 38
Dziamid Avatar answered Sep 18 '22 17:09

Dziamid