JLD
JLD

Reputation: 31

How to insertTable from sheet after specific text in google docs using google apps script?

I have got this code from Tanaike. It works but I don't understand the if statement.

Can someone explain this to me?

    var body = somedoc.getBody(); 
    var range = body.findText("#PLACEHOLDER#"); 
    var ele = range.getElement(); 

    if (ele.getParent().getParent().getType() === DocumentApp.ElementType.BODY_SECTION) { 
      var offset = body.getChildIndex(ele.getParent());
      body.insertTable(offset + 1, data);
    }

Upvotes: 0

Views: 367

Answers (1)

ziganotschka
ziganotschka

Reputation: 26796

Without seeing the rest of your code and question - what the code snippet does is to find a the text "PLACEHOLDER" in your document and to insert a table into the same StructuralElement as the one containing the Paragraph with your text.

It is useful to visualize the structure of a Google Docs document

enter image description here

enter image description here

In your case

  • The if statement verifies either the parent of the parent of ele is a BodySection
  • If the condition is fulfilled, it means that ele is a ParagraphElement
  • It also means that the parent of ele is a Paragraph
  • All StructuralElements have a childIndex
  • var offset = body.getChildIndex(ele.getParent()); finds the childIndex of the Paragraph that contains ele
  • The inserted table will have an index one higher than the Paragraph, this means that it will be inserted directly after the Paragraph

Upvotes: 1

Related Questions