Search code examples
jqueryelementparent-childvisible

$(element:visible) before or after $(this)


How do I determine if $(element:visible) is placed before or after $(this) in HTML?

My HTML code looks like this

<div class="wrapper" style="display:none;">
    <div class="title">1</div>
    <div class="text">Lorem Ipsum</div>
</div>

<div class="wrapper">
    <div class="title">2</div>
    <div class="text">Lorem Ipsum</div>
</div>

<div class="wrapper" style="display:none;">
    <div class="title">3</div>
    <div class="text">Lorem Ipsum</div>
</div>

<div class="wrapper" style="display:none;">
    <div class="title">4</div>
    <div class="text">Lorem Ipsum</div>
</div>

When I click on title 2 I want to know if there is visible $('.wrapper') before that title.


Solution

  • I hope this is what you need

    $(".title").click(function(){
      if($(this).parent().prev().is(":visible")) alert("Previous is visible!")
    });
    

    This tells you if the previous .wrapper (previous to clicked title) is visible.

    EDIT: This solves your updated question

    $(".title").click(function(){
      if($(this).parent().prevAll(".wrapper").is(":visible")) alert("Previous is visible!")
    });
    

    Hope this helps. Cheers