获取2个元素之间的元素

时间:2013-11-20 09:29:59

标签: javascript jquery html

我有这个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.glyphicon ,类 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();
        }
    }
});

3 个答案:

答案 0 :(得分:2)

尝试

$('.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

答案 1 :(得分:1)

尝试使用nextUntil()

<强> Live Demo

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

答案 2 :(得分:0)

也许使用 nextUntil (来自Jquery)
http://api.jquery.com/nextUntil/

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