获取2个元素之间的元素

Get elements between 2 elements

本文关键字:元素 之间 获取 2个      更新时间:2023-09-26

我有这个html:

<div class="categories">
    <div class="list-group">
        <a class="root list-group-item" id="427" style="display: block;"><span class="glyphicon indent0 glyphicon-chevron-down"></span><span>Home</span></a>
        <a class="list-group-item first active" id="428" style="display: block;"><span class="glyphicon indent1 glyphicon-chevron-right"></span><span>Images</span></a>
        <a class="list-group-item child" id="431" style="display: none;"><span class="glyphicon indent2"></span><span>Sub category</span></a>
        <a class="list-group-item first" id="429" style="display: block;"><span class="glyphicon indent1 glyphicon-chevron-right"></span><span>Videos</span></a>
        <a class="list-group-item child" id="432" style="display: none;"><span class="glyphicon indent2"></span><span>Another sub</span></a>
        <a class="list-group-item first" id="430" style="display: block;"><span class="glyphicon indent1"></span><span>Documents</span></a>
    </div>
</div>

我需要做的是选择a.active之间的所有元素。为了更好地解释这一点a.active有一个span.ghryphicon和类indent1,所以我需要在indent1和下一个indent1之间选择元素

我试图使用jQuery的nextAll函数,但无法正常工作:(

任何帮助都将不胜感激,

/r3plica

更新1

感谢Arun,这是我的脚本,现在可以工作了:

$(".glyphicon", treeRoot).on('click', function (e) {
    e.stopPropagation();
    var $glyph = $(this);
    var $item = $glyph.parent();
    var indent = $item.find(".glyphicon").prop('className').match(/'b(indent'd+)'b/)[1];
    console.log($item[0].outerHTML);
    console.log(indent);
    if (indent != undefined) {
        var $children = $item.nextUntil("a:has(." + indent + ")");
        console.log($children[0].outerHTML);
        if ($glyph.hasClass("glyphicon-chevron-right")) {
            $glyph
                .addClass('glyphicon-chevron-down')
                .removeClass("glyphicon-chevron-right");
            if ($children != null) $children.show();
        } else {
            $glyph
                .addClass('glyphicon-chevron-right')
                .removeClass("glyphicon-chevron-down");
            if ($children != null) $children.hide();
        }
    }
});

尝试

$('.active').nextUntil('a:has(.indent1)')

动态确定缩进值

var $active = $('.active');
var indent = $active.find('.glyphicon').prop('className').match(/'b(indent'd+)'b/)[1];
var $nexts = $active.nextUntil('a:has(.' + indent + ')');
console.log($nexts)

演示:Fiddle

尝试使用nextUntil()

实时演示

$('.active:has(.indent1)').nextUntil(':has(.indent1)')

可能使用next直到(来自Jquery)
看看http://api.jquery.com/nextUntil/

$('.active').nextUntil('.indent1');