Search code examples
javascriptjquerychildrenparents

select sibling and parent divs for javascript/jquery


hi just a general question. When making a javascript/jquery what would be the easiest way to indivate a particualr sibling div, or parent div, with a particular class.

The scenario is sometihng like this

<div class="a">
<div class="b"> </div>
<div class="c">
<div class="d"> </div> 
</div>
</div>

i would like to make clicking on div class b open div class c. I would also like to make clicking on div class d close div class c. div class b is a sibling div to div class c and div class c and div class c is a parent of div class d.

it is important that the javascript reffers to their parents or siblings because div class a (the container) will be repeated many times and each different instance of div class b and d should open different divs onclick, instead of all opening all instances with div class c.

so far i have thought of using something like an

event.target.getElementsByTagName("div")[]

- but actually i think this only looks for children of a particular div which really isnt what i want because im looking for indicating a sibling and a parent. anyone who knows how to do this who could point me in the right direction?


Solution

  • You can access the sibling via jQuery's .sibling() method:

    $(.b).click(function () {
      $(this).siblings('.c').addClass('open');
    });
    

    For more precise sibling selection you can use .prev('.c') or .next('.c').

    There is also a general sibling selector represented by the tilde ~:

    $('.b ~ .c');
    // or
    document.querySelectorAll('.b ~ .c');
    

    For closing .c when clicked on .d I would rely on event bubbling:

    $('.c').on('click', function (e) {
      if ($(e.target).is('.d')) $(this).removeClass('open');
    });