Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a jQuery selector to accomplish this task?

I have these 4 HTML snippets:

  • Siblings:

    <div class="a">...</div>
    <div class="b">...</div>        <!--selected-->
    <div class="b">...</div>        <!--not selected-->
    
  • Wrapped 1:

    <div class="a">...</div>
    <div>
        <div class="b">...</div>    <!--selected-->
    </div>
    <div class="b">...</div>        <!--not selected-->
    
  • Wrapped 2:

    <div>
        <div class="a">...</div>
    </div>
    <div>
        <div class="b">...</div>    <!--selected-->
    </div>
    <div class="b">...</div>        <!--not selected-->
    
  • Separated:

    <div class="a">...</div>
    <div>...</div>
    <div class="b">...</div>        <!--selected-->
    <div>...</div>
    <div class="b">...</div>        <!--not selected-->
    <div>...</div>
    <div class="b">...</div>        <!--not selected-->
    

How can I, with jQuery, select the next .b element for any given .a element, regardless of nesting?

I want something like this:

$('.a').each(function() {
    var nearestB = $(this)./*Something epically wonderful here*/;

    //do other stuff here
});
like image 490
Eric Avatar asked Jun 29 '10 13:06

Eric


1 Answers

Can you try this to see if it suits your case?

    $(document).ready(function () {
        var isA = false;

        $('div.a, div.b').each(function () {
            if ($(this).attr('class') == "a")
                isA = true;
            if ($(this).attr('class') == "b" && isA) {
                $(this).css("background", "yellow");
                isA = false;
            }
        });
    });

Regards...

like image 160
Padel Avatar answered Nov 09 '22 11:11

Padel