1

HTML:

<p><br style="clear:both;"></p>

我正在为一个项目使用 Wikipedia API,我正在清理 Wikipedia 的原始 HTML 输出,我一直在努力解决这个问题。如何<p>使用 jQuery 从 DOM 中删除这个特定元素.remove();?我只希望删除其中的<p>元素。<br style="clear:both;">

提前致谢!我一直在努力解决这个问题。

4

6 回答 6

5

那么,您是否要删除所有直接包含<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.

于 2013-07-17T22:16:33.243 回答
3

假设孩子是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

因为brdom谁的父母不是p

于 2013-07-17T22:15:05.677 回答
1

Try with:

$('p:has(br[style="clear:both;"])').remove();

JSBin Demo

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

于 2013-07-17T22:18:00.883 回答
0
$('p').filter(function(i) {
    return $(this).children('br').css('clear') == 'both';
}).remove();
于 2013-07-17T22:18:26.413 回答
0

the much safer method to do the task -

$('p').each(function(){
    if($(this).children().length === $(this).children('br').length)
      $(this).remove();
});
于 2013-07-17T22:48:49.433 回答
0
$('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!

于 2013-07-17T23:14:55.583 回答