Apps Script that counts the number of Heading 4 elements in a Google Doc

Apps Script Code

function countHeading4InDocument() {
const DOCID = 'YOUR_DOCUMENT_ID_HERE'; // Replace with your Document ID
const doc = DocumentApp.openById(DOCID);
const body = doc.getBody();
const paragraphs = body.getParagraphs();

let heading4Count = 0;

// Iterate through all paragraphs
for (let i = 0; i < paragraphs.length; i++) {
const paragraph = paragraphs[i];
if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING4) {
heading4Count++; // Increment counter if it's a Heading 4
}
}

Logger.log(`Number of Heading 4 elements: ${heading4Count}`);
return heading4Count; // Optional, in case you want to use it in another script
}

How It Works

  1. Access the Document:
    • The script opens the document using DocumentApp.openById(DOCID).
  2. Iterate Through Paragraphs:
    • The script loops through all paragraphs in the document using getParagraphs().
  3. Check for Heading 4:
    • For each paragraph, it checks if the heading style is HEADING4 using paragraph.getHeading().
  4. Count Heading 4:
    • A counter variable (heading4Count) is incremented for each paragraph identified as Heading 4.
  5. Log the Result:
    • The total count is logged in the Logs (View > Logs) for verification.

Steps to Use

  1. Set Up Apps Script:
    • Open Google Drive, go to Extensions > Apps Script, and paste the code into the script editor.
  2. Replace the Document ID:
    • Replace 'YOUR_DOCUMENT_ID_HERE' with the ID of your Google Doc.
  3. Run the Script:
    • Click the Run button in the Apps Script editor. Authorize the script if prompted.
  4. Check the Logs:
    • Open View > Logs to see the total number of Heading 4 elements.

Example

Document Content:

Heading 4: Section 1
Heading 2: Introduction
Heading 4: Section 2

Log Output:

Number of Heading 4 elements: 2

This script provides an efficient way to count Heading 4 elements, helping you analyze and manage your document’s structure.