Skip to content
Advertisement

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>

Advertisement

Answer

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.

Advertisement