The script only combines the first normal paragraph immediately following each H3 heading, rather than all subsequent paragraphs:
function combineH3WithFirstParagraph() {
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
}
i++; // Move to the next element regardless of whether a merge happened
} else {
i++; // Move to the next element
}
}
}
This script will now check each H3 heading and only merge it with the first normal paragraph that immediately follows it. It won’t affect any other paragraphs or headings. As before, be sure to test this on a copy of your document to ensure it behaves as expected.