Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements with only a   space using jQuery

Tags:

html

jquery

Is there a way to remove this

<p> </p>

using jQuery?

like image 328
Dom Avatar asked Oct 05 '09 16:10

Dom


3 Answers

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.

like image 54
Roatin Marth Avatar answered Oct 26 '22 19:10

Roatin Marth


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()
like image 26
Janson Avatar answered Oct 26 '22 19:10

Janson


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

    $("p").filter( function() {

        var html = $(this).html();

        if(html == '' || html == '&nbsp;')
            return true;

    }).addClass('emptyP');
like image 3
orbitory Avatar answered Oct 26 '22 19:10

orbitory