Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!