开发者

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.


The answer depends on what "empty" means. If the empty paragraphs are <p></p> then fireeyedboy's p:empty selector is the way to go. If there could be spaces or newlines or other such things then you'll probably want something like this:

$('p').each(function() {
    const $this = $(this);
    if($this.html().replace(/\s|&nbsp;/g, '').length === 0)
        $this.remove();
});

Example: http://jsfiddle.net/ambiguous/7L4WZ/

FCKEditor (not sure about CKEditor or TinyMCE) likes to add <p>&nbsp;</p> to the HTML so you might need the above somewhat ugly approach.


Try:

$( 'p:empty' ).remove();


you can try this...

$([selector]).is(":empty")   

it will return true if selector is empty..Working Demo


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!


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();
    });


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|&nbsp;/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.


/* Remove empty paragraphs with &nbsp; */
jQuery('p').each(function(){
    if( jQuery(this).html() == '&nbsp;' )
        jQuery(this).remove();
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜