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
- Target
Heading 4
:- The script identifies paragraphs styled as
Heading 4
usingparagraph.getHeading()
.
- The script identifies paragraphs styled as
- 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.
- The loop iterates through the paragraphs in reverse order (
- Insert Horizontal Line:
- A horizontal line is added above the
Heading 4
element usingbody.insertHorizontalRule(i)
.
- A horizontal line is added above the
- 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
- Set Up Apps Script:
- Open your Google Drive and navigate to Extensions > Apps Script.
- Paste the code into the script editor.
- 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
.
- Replace
- Run the Script:
- Click the Run button in the Apps Script editor. Authorize the script if prompted.
- Verify Changes:
- Open your Google Doc and confirm that a horizontal line has been added above each
Heading 4
.
- Open your Google Doc and confirm that a horizontal line has been added above each
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.