Jquery next siblings

I tried to solve this problem, but I cannot understand it without serious workarounds.

if I have the following HTML:

<ul>
    <li class="parent"> headertext </li>
    <li> text </li>
    <li> text </li>
    <li> text </li>
    <li class="parent"> headertext </li>
    <li> text </li>
    <li> text </li>
</ul>

Now, how now just select tags <li>after the first parent (or, secondly, for that matter)? Basically select <li>s class="parent"and the following siblings until you reach another <li>with the parent class.

I could rebuild the list using nested lists, but I don't want to do this. Any suggestions?

+3
source share
7 answers

, <li>, , <li> "". . jQuery , . . , , , jQuery, - .

+6

, , nextUntil(). "nextUntil", .

. -

$(".a").nextUntil(".b");

, -

$(".parent:first").nextUntil(".parent");
+11

, , , .

function getSibs( elem ) {
    var sibs = [];
    $(elem).nextAll().each( function() {
        if (!$(this).hasClass('parent')) {
            sibs.push(this);
        }
        else {
            return false;
        }
    });
    return $(sibs);
 }
+2

, jQuery , .

jQuery.fn.nextUntil = function(selector)
{
    var query = jQuery([]);
    while( true )
    {
        var next = this.next();
        if( next.length == 0 || next.is(selector) )
        {
            return query;
        }
        query.add(next);
    }
    return query;
}

// To retrieve all LIs avec a parent
$(".parent:first").nextUntil(".parent");

But you can better use a truly structured list for parent-child relationships

<ul>
<li class="parent"> <span>headertext</span>
    <ul>
    <li> text </li>
    <li> text </li>
    <li> text </li>
    </ul>
</li>
<li class="parent"> <span>headertext</span>
    <ul>
    <li> text </li>
    <li> text </li>
    </ul>
</li>
</ul>
+1
source
$("li.parent ~ li");
0
source
<html>
    <head>
        <script type="text/javascript">
            $(document).ready(function() {
                $("a").click(function() {
                    var fred = $("li").not('.parent').text();
                    $('#result').text(fred);           
                });
            });         
        </script>
    </head>
    <body>
        <a href="#">Click me</a>
        <ul>
            <li class="parent"> headertextA </li>
            <li> text1 </li>
            <li> text2 </li>
            <li> text3 </li>
            <li class="parent"> headertextB </li>
            <li> text4 </li>
            <li> text5 </li>
        </ul>
        <div id="result"></div>
    </body>
</html>
0
source

I know this is a very old thread, but JQuery 1.4 has a nextUntil method that can be useful for this purpose: http://api.jquery.com/nextUntil/

0
source

Source: https://habr.com/ru/post/1709762/


All Articles