Get siblings between 2 elements

后端 未结 4 420
旧时难觅i
旧时难觅i 2021-01-11 17:01

How can I get the elements between 2 other elements?

Like if I had:

相关标签:
4条回答
  • 2021-01-11 17:30

    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 讨论(0)
  • 2021-01-11 17:46

    With nextUntil [docs]:

    var $siblings = $('.c3').nextUntil('.c6');
    
    0 讨论(0)
  • 2021-01-11 17:47

    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;
        };
    
    0 讨论(0)
  • 2021-01-11 17:54

    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

    0 讨论(0)
提交回复
热议问题