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
- Access the Document:
- The script opens the document using
DocumentApp.openById(DOCID)
.
- The script opens the document using
- Iterate Through Paragraphs:
- The script loops through all paragraphs in the document using
getParagraphs()
.
- The script loops through all paragraphs in the document using
- Check for
Heading 4
:- For each paragraph, it checks if the heading style is
HEADING4
usingparagraph.getHeading()
.
- For each paragraph, it checks if the heading style is
- Count
Heading 4
:- A counter variable (
heading4Count
) is incremented for each paragraph identified asHeading 4
.
- A counter variable (
- Log the Result:
- The total count is logged in the Logs (
View > Logs
) for verification.
- The total count is logged in the Logs (
Steps to Use
- Set Up Apps Script:
- Open Google Drive, go to Extensions > Apps Script, and paste the code into the script editor.
- Replace the Document ID:
- Replace
'YOUR_DOCUMENT_ID_HERE'
with the ID of your Google Doc.
- Replace
- Run the Script:
- Click the Run button in the Apps Script editor. Authorize the script if prompted.
- Check the Logs:
- Open View > Logs to see the total number of
Heading 4
elements.
- Open View > Logs to see the total number of
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.