How do I remove empty p tags with jQuery?

后端 未结 6 877
后悔当初
后悔当初 2020-12-04 22:32

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

$

相关标签:
6条回答
  • 2020-12-04 22:49
    /* Remove empty paragraphs with   */
    jQuery('p').each(function(){
        if( jQuery(this).html() == ' ' )
            jQuery(this).remove();
    })
    
    0 讨论(0)
  • 2020-12-04 22:50

    Try:

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

    0 讨论(0)
  • 2020-12-04 22:54

    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!

    0 讨论(0)
  • 2020-12-04 23:03

    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() {
        var $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.

    0 讨论(0)
  • 2020-12-04 23:07

    you can try this...

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

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

    0 讨论(0)
  • 2020-12-04 23:12

    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.

    0 讨论(0)
提交回复
热议问题