Home > Blockchain >  How to select an element with jQuery using a variable in "contains" and remove the nearest
How to select an element with jQuery using a variable in "contains" and remove the nearest

Time:10-29

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

*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.

CodePudding user response:

In vanilla JS, will only find exact matches:

[...document.querySelectorAll('div')]
  .find(d=>d.textContent===String(comment_pk))
  .nextElementSibling
  .querySelector('.flag-container')
  .remove();
  • Related