开发者

Get siblings between 2 elements

How can I get the elements between 2 other elements?

Like if I had:

<div class="c1"></div>
<di开发者_Go百科v 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.


With nextUntil [docs]:

var $siblings = $('.c3').nextUntil('.c6');


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;
    };


If its only for styling purposes, and you don't want to use a Script, you can do it that way..

lets say that you want to style the elements between .c3 and .c6

.c3 ~ div
{
    /*special styling*/
}
div, .c6 ~ div
{
    /*normal styling*/
}

you can see it in action Here


You could also try the following:

var selected_elems = $("div").slice(2,6);

slice(): reduce the set of matched elements to a subset specified by a range of indices.

Documentation: http://api.jquery.com/slice/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜