jQuery: Find previous element with class

前端 未结 4 396
生来不讨喜
生来不讨喜 2020-12-17 10:22

I have a really simple problem.

How can I find the first previous element of another element? I tried the code below without success.

HTML:

&         


        
相关标签:
4条回答
  • 2020-12-17 10:54
    $('.C').click(function() {
       alert($(this).closest('.B').prev('.A').html());
    });
    
    0 讨论(0)
  • 2020-12-17 11:03

    Try this:

    $('.C').click(function() {
    
            alert($(this).parent().prev('.A').html());
    
    });
    
    0 讨论(0)
  • 2020-12-17 11:03

    if you want to target closest children of top parent you can do so as something define below.

    lets assume you have an HTML like

    <div class="top-parent">
      <div class="parent">
        <button class="add-button">Child of 1st Parent DIV</button>
      </div>
      <div class="parent">
        <button class="add-button">Child of 2nd Parent DIV</button>
      </div>
    </div>
    <script>
    $(document).on('click','.add-button',function(){
       $(this).parents('.parent').prev().closest('.parent').find('.add-button').text('im clicked by one of the button next to my parent')
       $(this).parents('.parent').remove();
    })
    </script>
    

    similarly if you want to target grandparent next parent containers children just change .prev() to .next()

    hope i made it simple to define :)

    0 讨论(0)
  • 2020-12-17 11:11

    If you are trying to get the preceding sibling, use .prev().

    If you are trying to get the sibling of the parent (like in your example) use .parent().prev().

    0 讨论(0)
提交回复
热议问题