Search code examples
google-apps-scriptgoogle-docsparagraph

How to exclude table cells paragraphs from getParagraphs() in DocumentApp, apps script


I need to get all the paragraphs from a google document. For that, I am using body.getParagraphs(). The problem is, in any document, if any table exists, the body.getParagraphs() method takes all the table cells as a paragraph and returns as a paragraph. Now what I want is to get all the paragraphs only, from a document and exclude the table and table cells from that. How can I achieve this?

Thanks!


Solution

  • I believe your goal as follows.

    • You want to retrieve the paragraphs except for the table cell using Google Apps Script.

    In this case, how about checking the element type? When this is reflected to a script, it becomes as follows.

    Sample script:

    Please copy and paste the following script to the script editor of Google Document.

    function myFunction() {
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      const paragraphs = body.getParagraphs();
      
      const res = paragraphs.filter(p => p.getParent().getType() != DocumentApp.ElementType.TABLE_CELL);
      
      // do something
    
    }
    
    • In this sample script, the values of paragraphs include the paragraphs of table cell.
    • By filtering the element type, res can have only the paragraphs except for the table cell.

    References: