Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

finding closest following sibling in jQuery

I have the following code in HTML:

$(".remove-post").click((event) => {
      $(event.target).fadeOut();
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="side-bar">
  <button class="remove-post"> delete </button>
  <a class="list">
    <p>post title</p>
  </a>

  <button class="remove-post"> delete <button>
  <a class="list"><p>another post title</p></a>
</div>

every time that I click on a delete button I want to delete the closest "a" tag with the paragraph inside it as well as the delete button by itself. I was able to delete the button but can’t target the closest a tag to that clicked button
I wrote it in jQuery

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming you want to remove the next a.list sibling, use .next()

$(".remove-post").on("click", function() {
  const btn = $(this)
  btn.add(btn.next("a.list")).fadeOut()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="side-bar">
  <button class="remove-post">delete</button>
  <a class="list"><p>post title</p></a>

  <button class="remove-post">delete</button>
  <a class="list"><p>another post title</p></a>
</div>

jQuery’s .add() is used here to collect both the <button> and <a> so you can fade them out together.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading