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

173
Visualizações
How to select an element with jQuery using a variable in "contains" and remove the nearest el with class Foo

I'm trying to select an element using a variable in the selector to remove the nearest element with class flag-container. However, the element isn't removed when I trigger the function.

function remove_div() {
    let comment_pk = 1
    $("div:contains('" + comment_pk + "')").closest('.flag-container').remove()
}

$('#trigger').click(function() {
    remove_div()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div hidden class="comment-pk">1</div>
<div class="drilled-hierarchy">
   <div class="flag-container">
      To be removed
   </div>
</div>


<button id="trigger"> Remove </button>

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

0

The issue in your logic is that closest() travels up the DOM along ancestor elements. The .flag-container you're looking to target is instead a child of a sibling to the original div.

Therefore you can use next()* and find() instead:

function remove_div() {
  let comment_pk = 1
  $("div:contains('" + comment_pk + "')").next('.drilled-hierarchy').find('.flag-container').remove()
}

$('#trigger').click(function() {
  remove_div()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div hidden class="comment-pk">1</div>
<div class="drilled-hierarchy">
  <div class="flag-container">
    To be removed
  </div>
</div>


<button id="trigger">Remove</button>

*using a selector string argument in the next() call is optional in this case, but saves unexpected bugs later. siblings() may also be appropriate depending on your exact use case.

about 4 years ago · Juan Pablo Isaza Relatório

0

In vanilla JS, will only find exact matches:

[...document.querySelectorAll('div')]
  .find(d=>d.textContent===String(comment_pk))
  .nextElementSibling
  .querySelector('.flag-container')
  .remove();
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