Remove elements with only a   space using jQuery

后端 未结 8 674
北恋
北恋 2020-11-30 07:34

Is there a way to remove this

using jQuery?

相关标签:
8条回答
  • 2020-11-30 08:06
    $("p").filter( function() {
                return $.trim($(this).html()) == '';
            }).remove()
    

    I used this to remove empty paragraph that contains not element such as IMG, Input, Select, etc.

    0 讨论(0)
  • 2020-11-30 08:07

    This could be a better solution for CMSs. Some rich text editors add   inside empty paragraphs.

        $("p").filter( function() {
    
            var html = $(this).html();
    
            if(html == '' || html == ' ')
                return true;
    
        }).addClass('emptyP');
    
    0 讨论(0)
  • 2020-11-30 08:14

    give it an id (to get the selector).

    <p id="myP"></p>
    
    
    <script>
    
    $("#myP").remove();
    
    </script>
    
    0 讨论(0)
  • 2020-11-30 08:21

    Try:

    $('p')
        .filter(function() {
            return $.trim($(this).text()) === '' && $(this).children().length == 0
        })
        .remove()
    

    What that does is it finds all the <p>s that have nothing in them, and removes them from the DOM.

    0 讨论(0)
  • 2020-11-30 08:23

    As Greg mentions above, testing the trimmed .text() will remove paragraphs w/ no text, but do have a self-contained element like the <img> tag. To avoid, trim the .html() return. As text is considered a child element in the DOM, you'll be set.

    $("p").filter( function() {
        return $.trim($(this).html()) == '';
    }).remove()
    
    0 讨论(0)
  • 2020-11-30 08:24

    Probably same answer as here, try to do this on code behind.

    With jquery i'll use this:

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

    Also you could use .empty(), that will remove all child nodes from the set of matched elements.

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