HTML:
<p><br style="clear:both;"></p>
我正在为一个项目使用 Wikipedia API,我正在清理 Wikipedia 的原始 HTML 输出,我一直在努力解决这个问题。如何<p>使用 jQuery 从 DOM 中删除这个特定元素.remove();?我只希望删除其中的<p>元素。<br style="clear:both;">
提前致谢!我一直在努力解决这个问题。
HTML:
<p><br style="clear:both;"></p>
我正在为一个项目使用 Wikipedia API,我正在清理 Wikipedia 的原始 HTML 输出,我一直在努力解决这个问题。如何<p>使用 jQuery 从 DOM 中删除这个特定元素.remove();?我只希望删除其中的<p>元素。<br style="clear:both;">
提前致谢!我一直在努力解决这个问题。
那么,您是否要删除所有直接包含<br>具有给定样式属性的 a 的元素?
$('br[style="clear:both;"]').parent().remove();
This is decently conservative in that it only matches br tags of the form you describe—though it might be worth being even more conservative by sticking a p selector in that parent call. But, it's also sufficiently conservative that it might not catch small variations on this markup, so keep an eye out.
假设孩子是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
Try with:
$('p:has(br[style="clear:both;"])').remove();
As Matchu pointed out be careful as this will remove <p> elements with <br style="clear:both;"> inside, so in certain specific cases (if there's anything else inside the <p>) it could remove more than you expect...
$('p').filter(function(i) {
return $(this).children('br').css('clear') == 'both';
}).remove();
the much safer method to do the task -
$('p').each(function(){
if($(this).children().length === $(this).children('br').length)
$(this).remove();
});
$('p').each(function(){
if($(this).children('br').length == 1) {
$(this).remove();
}
});
This worked for me. It seems 'clear:both;' was generated by the browser. Thanks for all the ideas and suggestions so I could figure this out!