title: Google Docs Apps script - how to remove really empty paragraphs
body: <p>How we can remove <strong>really</strong> 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?
  <a href="https://developers.google.com/apps-script/reference/document/text#gettext" rel="nofollow noreferrer">getText()</a> and <a href="https://developers.google.com/apps-script/reference/document/text#editastext" rel="nofollow noreferrer">editAsText()</a> gives nothing to this.</p>
  
  <pre><code>var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var docParagraphs = doc.getBody().getParagraphs();
  
  for (var i = 0; i &lt; docParagraphs.length; i++) {
      if (docParagraph[i].getText() === '') {
        docParagraphs[i].removeFromParent();
      }
  }
  </code></pre>
  
  <p>I know there are topic related to ~similar problem, but not the same. <a href="https://stackoverflow.com/questions/39962369/how-to-find-and-remove-blank-paragraphs-in-a-google-document-with-google-apps-sc">How to find and remove blank paragraphs in a Google Document with Google Apps Script?</a></p>
  
  <p>UPD: correct answer:</p>
  
  <pre><code>var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  
  for (var i = 0; i &lt; doc.getBody().getParagraphs().length; i++) {
    if (docParagraph[i].getText() === '') {
      if (docParagraph_i.getNumChildren() == 0 &amp;&amp; i &lt; (docParagraphs.length - 1)) {
        docParagraph[i].removeFromParent();
      }
    }
  }
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>&amp;&amp; i &lt; (...)
  </code></pre>
  
  <p>because last paragraph can't be deleted and throws an error.</p>