HTML:
<p><br style="clear:both;"></p>
I'm using the Wikipedia API for a project, and I'm cleaning up Wikipedia's raw HTML output and I've been struggling with this problem. How do I remove this specific <p>
element from the DOM with jQuery using .remove();
? I only want the <p>
element with <br style="clear:both;">
inside of it to be removed.
Thanks in advance! I've been struggling with this problem.
So, you're trying to remove all elements that directly contain a <br>
with the given style attribute?
$('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.
suppose the child is br
itself, then the code will be -
$('p>br').closest('p').remove();
or use
$('p>br[style="clear:both;"]').closest('p').remove();
or use the parent function
$('br[style="clear:both;"]').parent('p').remove();
but don't make it
$('br[style="clear:both;"]').parent().remove(); // Don't use this
because there may be many br
possible in the dom
whose parent is not 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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.