Creating a Google Apps Script to combine paragraph content with a heading (H3) in a Google Docs document involves writing a script that iterates through the document’s elements, identifies the H3 headings, and then merges the following paragraphs with these headings.
Here’s a basic script to get you started:
function combineH3WithParagraphs() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var elements = body.getNumChildren();
var i = 0;
while (i < elements) {
var element = body.getChild(i);
// Check if the element is a heading of type H3
if (element.getType() === DocumentApp.ElementType.PARAGRAPH && element.asParagraph().getHeading() === DocumentApp.ParagraphHeading.HEADING3) {
var h3Text = element.asParagraph().getText();
var nextElement = body.getChild(i + 1);
// Check if the next element is a normal paragraph
if (nextElement && nextElement.getType() === DocumentApp.ElementType.PARAGRAPH && nextElement.asParagraph().getHeading() === DocumentApp.ParagraphHeading.NORMAL) {
var paragraphText = nextElement.asParagraph().getText();
// Combine H3 text with the paragraph text
element.asParagraph().setText(h3Text + " " + paragraphText);
// Remove the original paragraph
body.removeChild(nextElement);
elements--; // Update the elements count as one is removed
} else {
i++; // Move to the next element
}
} else {
i++; // Move to the next element
}
}
}
How to Use This Script
- Open your Google Docs document.
- Go to
Extensions > Apps Script
. - Delete any code in the script editor and paste the above script.
- Save and name your project.
- Run the function
combineH3WithParagraphs
from the Apps Script editor. The first time you run it, you’ll need to authorize the script. - Return to your document and you’ll see that any paragraph immediately following an H3 heading has been merged with it.
Important Notes
- This script will combine each H3 heading with the immediately following paragraph, if it’s a normal paragraph.
- The script does not combine subsequent paragraphs or handle complex scenarios (like lists or tables after the H3 heading).
- Always test scripts like these on a copy of your document to prevent accidental data loss.
![](https://i0.wp.com/basescripts.com/wp-content/uploads/2024/01/image-77.png?resize=354%2C117&ssl=1)