简体   繁体   中英

Get immediate child using nextUntil

I have some 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 glyphicon-chevron-right indent2"></span><span>Sub category</span></a>
        <a class="list-group-item child" id="433" style="display: none;"><span class="glyphicon indent3"></span><span>Super sub</span></a>
        <a class="list-group-item first" id="429" style="display: block;"><span class="glyphicon glyphicon-chevron-right indent1"></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>

and I have this function:

$(".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];

    if (indent != undefined) {
        var $children = $item.nextUntil("a:has(." + indent + ")");

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

So basically, when the icon is clicked, it shows or hides the children. The problem is, it shows all children (indent2 and indent3) but I just want it to show the immediate children (indent2 in this example).

Could someone give me some insight on how to do this?

Cheers,

/r3plica

Try

var num = parseInt(indent.match(/(\d+)$/)[1], 10);
var $children = $item.nextUntil("a:not(:has(.indent" + (num + 1) + "))");

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM