'How do I remove empty p tags with jQuery?
The platform I'm building a website on produces empty p tags in wysiwyg mode. How can I take these out?
Something like this, perhaps...
$("<p> </p>").remove();
Although the code above does nothing.
Solution 1:[1]
Try:
$( 'p:empty' ).remove();
Solution 2:[2]
you can try this...
$([selector]).is(":empty")
it will return true if selector is empty..Working Demo
Solution 3:[3]
I'm a little late to the party, but I found this thread recently as I was looking to solve this issue as well.
I came up with a Vanilla JS solution here, which worked for me:
var p = document.querySelectorAll('p:empty');
for(var i = p.length - 1; i > -1; i-- ) {
p[i].parentNode.removeChild(p[i]);
}
It basically does (exactly) what fireeyedboy suggested, but without jQuery.
It also appears to perform better than jQuery as well: http://jsperf.com/remove-empty-elements-javascript-vs-jquery
Hope this helps!
Solution 4:[4]
If anyone need this for WP site, so use these:
jQuery('p').each(function() {
var $this = jQuery(this);
if($this.html().replace(/\s| /g, '').length == 0)
$this.remove();
});
Solution 5:[5]
Thanks "mu is too short",
I've tried your code It works but I need to wrap it in jQuery(document).ready(function() {});
The full code worked for me is:
jQuery(document).ready(function() {
jQuery('p').each(function() {
var $this = jQuery(this);
if($this.html().replace(/\s| /g, '').length == 0) {
$this.remove();
}
});
});
I don't know why this happens, My jQuery/JS is not so good, I'm learning it ;).
Hope this help another person like me.
Thanks.
Solution 6:[6]
/* Remove empty paragraphs with */
jQuery('p').each(function(){
if( jQuery(this).html() == ' ' )
jQuery(this).remove();
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Decent Dabbler |
| Solution 2 | Vivek |
| Solution 3 | ItsJonQ |
| Solution 4 | shakil |
| Solution 5 | |
| Solution 6 | Fabio Manzo |
