1
  • 2

    How do I use nextUntil with a child selector?

    Given this markup:

    <ul>
        <li><a class="level1 selected">1</a></li>
        <li><a class="level2">2</a></li>
        <li><a class="level2">3</a></li>
        <li><a class="level2">4</a></li>
        <li><a class="level1">1</a></li>
        <li><a class="level2">5</a></li>
        <li><a class="level2">6</a></li>
        <li><a class="level2">7</a></li>
        <li><a class="level1">1</a></li>
    </ul>
    
          

    How do I select tags LI

    whose childred has a class level2

    next to a tag LI

    whose child has a class selected

    ?

    My original code is crashing because I cannot use the nextUntil () function.

    // Selects the parent of the select A tag    
    var selectedParent = $("ul li a.selected.level1").parents("li");
    
    selectedParent.nextUntil("li a.level1").each(function () {
        $(this).children().addClass("on");
    });
    
          

    +3


    source to share


    2 answers


    $lvl1 = $('a:not(.level2)').closest('li');
    $lvl2 = $('a.selected').closest('li').nextUntil($lvl1);
    
          

    or in one line:



    $lvl2 = $('a.selected').closest('li').nextUntil($('a:not(.level2)').closest('li'));
    
          

    http://jsfiddle.net/mblase75/jKCrH/

    +3


    source


    Instead of using complex selectors (which will traverse too many objects inside jQuery), you can create a custom function for that. I think it will be more efficient. Try the DEMO HERE



    $.fn.nextTillList1 = function () {
        return this.each(function () {
            var $item = $(this).next("li");
            while($item.find(".level1").length <= 0) {
                $item.children().addClass("on");
                $item = $item.next("li");
            }
        });
    };
    
    // Selects the parent of the select A tag    
    var selectedParent = $("ul li a.selected.level1").parents("li");
    
    // Call custom function
    selectedParent.nextTillList1();
    
          

    +1


    source







    All Articles