10

My writers have a bad habit of creating empty paragraphs. (I.e., paragraphs that have nothing inside them, like:

<p></p>

Is there a jQuery function that removes "empty" paragraphs. Here's what I've tried:

$('p').remove(":contains(' ')"); // nope! bad logic, all p's have empty spaces 

$("p:empty").remove() // nope, doesn't work, doesn't remove any p's

Anything else I should try?

a53-416
  • 3,585
  • 6
  • 34
  • 44

6 Answers6

21

$("p:empty").remove() works for me (demo at http://jsfiddle.net/AndyE/XwABG/1/). Make sure your elements are actually empty and don't contain any white space.

You can always use filter():

// Trimming white space
$('p').filter(function () { return $.trim(this.innerHTML) == "" }).remove();

// Without trimming white space
$('p').filter(function () { return this.innerHTML == "" }).remove();

Working demo: http://jsfiddle.net/AndyE/XwABG/

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • could also user `this.innerHTML` or `$(this).text()` – Naftali Oct 19 '11 at 15:38
  • @Neal: switched to `this.innerHTML` for performance. My knee-jerk reaction is usually to go for text, but that requires browser checks or recursion. – Andy E Oct 19 '11 at 15:43
2

I think this will work with any number of spaces (sorry I'm not sure I understood whether there was spaces in the paragraphs or not):

$("p").each(function(){
  if ($.trim($(this).text()) == ""){
    $this.remove();
  } 
});
Arthur Frankel
  • 4,695
  • 6
  • 35
  • 56
1

If you want to extend Andy's answer to non-breakable spaces (and use string's trim() method instead of jquery's), you may use:

$('p').filter(function () { 
    return this.innerHTML
        .replace("&nbsp;"," ")
        .trim() 
        == "" 
}).remove();
RockyRoad
  • 640
  • 5
  • 17
1

This is plain old JavaScript and it's very fast:

[].filter.call(document.getElementsByTagName("p"), function(elem){return elem.childElementCount==0 && elem.textContent.trim()==''})
    .forEach(function(elem){elem.parentNode.removeChild(elem)})

This one is even faster:

var paragraphs = document.getElementsByTagName("p"); 
for (var i = 0, len = paragraphs.length; i < len; i++) {
    var elem = paragraphs[i];
    if (elem.childElementCount == 0 && elem.textContent.trim() == '') {
        elem.parentNode.removeChild(elem);
        i--;
        len--;
    }
}
JukkaP
  • 1,994
  • 1
  • 14
  • 7
0

If the empty paragraphs are

then fireeyedboy's p:empty selector is the way to go :-
$('p').each(function() {
    var $this = $(this);
    if($this.html().replace(/\s|&nbsp;/g, '').length == 0)
        $this.remove();
});
Rahul Shinde
  • 1,522
  • 1
  • 15
  • 17
0

Use .each to iterate over all paragraphs and check for innerHTML empty and remove those

Moin Zaman
  • 25,281
  • 6
  • 70
  • 74