Apps Script code that adds a horizontal line above each Heading 4

Apps Script Code

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

// Iterate through the paragraphs in reverse order
for (let i = paragraphs.length - 1; i >= 0; i--) {
const paragraph = paragraphs[i];

// Check if the paragraph is a Heading 4
if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING4) {
// Insert a horizontal line above the Heading 4 element
body.insertHorizontalRule(i);
Logger.log(`Added horizontal line above Heading 4 at index: ${i}`);
}
}

Logger.log("Processed all Heading 4 elements.");
}

How It Works

  1. Target Heading 4:
    • The script identifies paragraphs styled as Heading 4 using paragraph.getHeading().
  2. Iterate Backwards:
    • The loop iterates through the paragraphs in reverse order (for (let i = paragraphs.length - 1; i >= 0; i--)) to ensure that the indices remain consistent when inserting horizontal lines.
  3. Insert Horizontal Line:
    • A horizontal line is added above the Heading 4 element using body.insertHorizontalRule(i).
  4. Logging:
    • Logs are added for each update, making it easier to debug and verify the changes.

Example

Before:

This is a normal paragraph.
Heading 4: Section 1
Heading 4: Section 2
This is another paragraph.

After:

This is a normal paragraph.
---------------------
Heading 4: Section 1
---------------------
Heading 4: Section 2
This is another paragraph.

Steps to Use

  1. Set Up Apps Script:
    • Open your Google Drive and navigate to Extensions > Apps Script.
    • Paste the code into the script editor.
  2. Replace the Document ID:
    • Replace 'YOUR_DOCUMENT_ID_HERE' with the ID of your Google Doc. The ID is found in the URL between /d/ and /edit.
  3. Run the Script:
    • Click the Run button in the Apps Script editor. Authorize the script if prompted.
  4. Verify Changes:
    • Open your Google Doc and confirm that a horizontal line has been added above each Heading 4.

Why Start from the End?

Starting from the end ensures that inserting a horizontal line does not affect the indices of subsequent paragraphs. This is crucial for maintaining consistent behavior in iterative scripts.