0

How we can remove really empty paragraphs from Google Document? This code will remove any paragraphs that contains images, hr's etc. Can't understand how to check if a paragraph really empty? getText() and editAsText() gives nothing to this.

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var docParagraphs = doc.getBody().getParagraphs();

for (var i = 0; i < docParagraphs.length; i++) {
    if (docParagraph[i].getText() === '') {
      docParagraphs[i].removeFromParent();
    }
}

I know there are topic related to ~similar problem, but not the same. How to find and remove blank paragraphs in a Google Document with Google Apps Script?

UPD: correct answer:

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();

for (var i = 0; i < doc.getBody().getParagraphs().length; i++) {
  if (docParagraph[i].getText() === '') {
    if (docParagraph_i.getNumChildren() == 0 && i < (docParagraphs.length - 1)) {
      docParagraph[i].removeFromParent();
    }
  }
}

I've changed for expression too to limit i by a current elements count, not stored in variable. Because elements are deleted (or in other implementation added, for example) there will be error when no paragraphs but cycle will want to get them.

&& i < (...)

because last paragraph can't be deleted and throws an error.

Community
  • 1
  • 1
Bowman
  • 15
  • 5

1 Answers1

0

You will want to check for children in the paragraph

paragraph.getNumChildren() //returns the number of children

Hink
  • 2,271
  • 1
  • 11
  • 8
  • I tried .getNumChildren() before, and i tried .getChild().getType() before few times with no luck, but your answer told me to recheck again. I did a pause after asking question and now with clear mind found that i've used .getNumChildren() not to paragraph but for first possible child of it (by .getChild()) and didn's understand why it throws an error even in .getChild(). First such paragraph was really blank... Thanx! – Bowman Feb 13 '17 at 22:09