Listing contents of paragraphs using Google Apps Script

function updateParagraph() {
  const doc = DocumentApp.getActiveDocument();
  const docBody = doc.getBody();
  const docParagraph = docBody.getChild(1);
  Logger.log(docParagraph.getText());
  const paraList = docBody.getParagraphs();
  Logger.log(paraList.length);
  paraList.forEach(par => {
    Logger.log(par.getText());
  });
}
  1. The updateParagraph() function is declared.
  2. const doc = DocumentApp.getActiveDocument() retrieves the active document object.
  3. const docBody = doc.getBody() gets the body of the document.
  4. const docParagraph = docBody.getChild(1) retrieves the second child element of the document’s body. Note that the getChild() method uses a zero-based index, so getChild(1) refers to the second child element. If you want to target the first child element, use getChild(0).
  5. Logger.log(docParagraph.getText()) logs the text content of the docParagraph using Logger.log(). The Logger.log() method is used in Apps Script to log output that can be viewed in the script editor. It helps with debugging and reviewing information. The text content of the paragraph will be logged in the script editor’s logs.
  6. const paraList = docBody.getParagraphs() retrieves a list of all paragraphs in the document body.
  7. Logger.log(paraList.length) logs the number of paragraphs in the document body using Logger.log().
  8. paraList.forEach(par => { Logger.log(par.getText()); }) iterates through each paragraph in paraList using a forEach loop. For each paragraph, the text content of the paragraph is logged using Logger.log(). This allows you to view the text content of each paragraph in the script editor’s logs.

To use this code:

  1. Open the script editor in your Google Docs document.
  2. Paste the code into the editor.
  3. Save the project.
  4. Run the updateParagraph function by clicking the play button or by going to “Run” -> “Run function” -> “updateParagraph”.
  5. Check the logs in the script editor to view the text content of the targeted paragraph (docParagraph.getText()), the number of paragraphs in the document body (paraList.length), and the text content of each paragraph in the document.

Remember to adjust the index in getChild() based on your specific requirements and the structure of your document.