Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
finding closest 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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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 class="side-bar">
    <div class="wrapper">
        <button class="remove-post">Delete<button>
        <a class="list">Another post title</a>
     </div>

    <div class="wrapper">
      <button class="remove-post">Delete <button>
      <a class="list">Another post title</a>
    </div>
</div>

If you do so, then you can use this:

$(".remove-post").on("click", function () {
    $(this).parent().fadeOut()
})
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda