[英]jQuery remove element that contains another element with the class of ___
[英]How to select an element with jQuery using a variable in "contains" and remove the nearest el with class Foo
我正在嘗試使用選擇器中的變量來選擇一個元素,以刪除最近的具有類flag-container
元素。 但是,當我觸發該功能時,該元素不會被刪除。
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>
您邏輯中的問題是closest()
沿着祖先元素向上移動 DOM。 您要定位的.flag-container
是原始div
兄弟的孩子。
因此,您可以使用next()
* 和find()
代替:
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>
*在這種情況下,在next()
調用中使用選擇器字符串參數是可選的,但稍后會保存意外錯誤。 siblings()
也可能是合適的,具體取決於您的具體用例。
在 vanilla JS 中,只會找到完全匹配的:
[...document.querySelectorAll('div')]
.find(d=>d.textContent===String(comment_pk))
.nextElementSibling
.querySelector('.flag-container')
.remove();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.