Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda