![](/img/trans.png)
[英]How to append an element after specific child element using jquery?
[英]How to delete an element in jQuery with a specific child?
HTML:
<p><br style="clear:both;"></p>
我正在為項目使用Wikipedia API,並且正在清理Wikipedia的原始HTML輸出,並且一直在努力解決此問題。 如何使用jQuery使用.remove();
從DOM中刪除此特定<p>
元素.remove();
? 我只希望刪除其中具有<br style="clear:both;">
的<p>
元素。
提前致謝! 我一直在努力解決這個問題。
因此,您要刪除具有給定樣式屬性的所有直接包含<br>
元素嗎?
$('br[style="clear:both;"]').parent().remove();
這是相當保守的,因為它僅匹配您描述的形式的br
標簽-盡管通過在parent
調用中插入p
選擇器可能更加保守。 但是,它也非常保守,可能不會在此標記上引起小的變化,因此請注意。
假設孩子本身是br
,那么代碼將是-
$('p>br').closest('p').remove();
或使用
$('p>br[style="clear:both;"]').closest('p').remove();
或使用父函數
$('br[style="clear:both;"]').parent('p').remove();
但是不要做
$('br[style="clear:both;"]').parent().remove(); // Don't use this
因為可能有很多br
可能在dom
的父不是p
嘗試:
$('p:has(br[style="clear:both;"])').remove();
正如Matchu指出的那樣,要小心,因為這會刪除內部帶有<br style="clear:both;">
<p>
元素,因此在某些特定情況下(如果<p>
內還有其他內容),它可能會刪除比您更多的元素期望...
$('p').filter(function(i) {
return $(this).children('br').css('clear') == 'both';
}).remove();
執行任務的更安全的方法-
$('p').each(function(){
if($(this).children().length === $(this).children('br').length)
$(this).remove();
});
$('p').each(function(){
if($(this).children('br').length == 1) {
$(this).remove();
}
});
這對我有用。 似乎“很清楚:兩者都”; 是由瀏覽器生成的。 感謝您的所有想法和建議,以便我能解決!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.