Google Script, How to identify all 'Header3' elements within a google doc?

Viewed 124

I'm a beginner working with Google Apps Script to pull data from a Google Doc, and I need some help...

I have a Google Doc that has a ton of cooking recipes. I'd like to write a function that randomly selects 4 recipes, and emails me the ingredients so I know what to shop for that week. All my recipes titles are 'Heading 3', with the ingredients as bullet points below them. I'm fully open to modifying the formatting if need be.

I'm trying to have my script identify all text that is of type 'Heading 3' as my starting point. That way I can randomly select from that list of recipes, but cannot find a way to do so. Below is what I have so far:

function onOpen() {
  var ui = DocumentApp.getUi();
  ui.createMenu('Generate Weekly Shopping List')
      .addItem('Send Email', 'generateMenu')
      .addToUi();
}

function generateMenu() {
  //I may need the doc and body variables later...  
  //Get the latest contents of the menu
  var doc = DocumentApp.openById("<my doc ID here>");
  
   //Assign a variable to the body of the doc
  var body = doc.getBody();

  //declare variable holding the search criteria
  var searchType = DocumentApp.ParagraphHeading.HEADING3;
  
  //search the body based on the search criteria
  var searchResult = body.findElement(searchType);  

  // Get the email address of the active user - that's you.
  var email = Session.getActiveUser().getEmail();

  // Send yourself an email with list.
  GmailApp.sendEmail(email, "Shopping List For The Week", "Here is the shopping list:" + searchResult);
  
}
1 Answers

From the question

I'm trying to have my script identify all text that is of type 'Heading 3' as my starting point. That way I can randomly select from that list of recipes, but cannot find a way to do so. Below is what I have so far:

Use getHeading

Retrieves the ParagraphHeading.

Then compare the result to DocumentApp.ParagraphHeading.HEADING3.

To do the above first you will have to get all the paragraphs then iterate over them to get the heading.


Regarding

//declare variable holding the search criteria
 var searchType = DocumentApp.ParagraphHeading.HEADING3;
  
//search the body based on the search criteria
var searchResult = body.findElement(searchType);  

DocumentApp.ParagraphHeading.HEADING3 can't be used as an argument of findElement as it's is not an ElementType


Related

Related