Home > database >  finding closest sibling in jQuery
finding closest sibling in jQuery

Time:02-01

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 >
  <button > delete </button>
  <a >
    <p>post title</p>
  </a>

  <button > delete <button>
  <a ><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

CodePudding user response:

If the button will always stay before paragraph you can do:

$(".remove-post").on("click", function () {
    $(this).next(".list").fadeOut()
    $(this).fadeOut()
})

I would recommend you to wrap the paragraph and the button together like:

<div >
    <div >
        <button >Delete<button>
        <a >Another post title</a>
     </div>

    <div >
      <button >Delete <button>
      <a >Another post title</a>
    </div>
</div>

If you do so, then you can use this:

$(".remove-post").on("click", function () {
    $(this).parent().fadeOut()
})

CodePudding user response:

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 >
  <button >delete</button>
  <a ><p>post title</p></a>

  <button >delete</button>
  <a ><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.

  •  Tags:  
  • Related