How to Update Heading 2 to Heading 1 in Google Docs Using Google Apps Script

Introduction

Google Docs provides a robust set of formatting tools, but sometimes, you may need to make bulk changes to your document styles programmatically. Instead of manually changing each heading, you can automate the process using Google Apps Script.

In this tutorial, we’ll walk through a simple Google Apps Script that updates all Heading 2 styles to Heading 1 in a Google Docs document.


Why Use Google Apps Script?

Google Apps Script is a cloud-based JavaScript platform that allows you to automate tasks across Google Workspace applications, such as Google Docs, Sheets, and Drive.

By using a script, you can quickly modify multiple heading styles in a document without repetitive manual adjustments.


Steps to Create the Script

Follow these steps to create and run your script:

Step 1: Open Google Apps Script

  1. Open your Google Docs document.
  2. Click on Extensions → Apps Script.
  3. Delete any existing code in the script editor.

Step 2: Add the Code

Copy and paste the following script into the Apps Script editor:

function updateHeading2ToHeading1() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();

// Get all paragraphs in the document
var paragraphs = body.getParagraphs();

// Loop through paragraphs and update Heading2 to Heading1
paragraphs.forEach(function(paragraph) {
if (paragraph.getHeading() == DocumentApp.ParagraphHeading.HEADING2) {
paragraph.setHeading(DocumentApp.ParagraphHeading.HEADING1);
}
});

Logger.log("Updated all Heading 2 to Heading 1.");
}

Step 3: Run the Script

  1. Click the Run button ▶️ in the Apps Script editor.
  2. If prompted, grant the necessary permissions for the script to modify your document.
  3. The script will update all Heading 2 styles to Heading 1 automatically.

How the Script Works

  • The script fetches the active document using DocumentApp.getActiveDocument().
  • It retrieves all paragraphs from the document’s body.
  • It loops through the paragraphs and checks if the heading style is HEADING2.
  • If a paragraph is HEADING2, it updates it to HEADING1.
  • Finally, the script logs a message to confirm the update.

Use Cases

This script is particularly useful for:
✅ Formatting large documents efficiently.
✅ Standardizing heading structures in reports or articles.
✅ Saving time on repetitive formatting tasks.


Conclusion

With just a few lines of Google Apps Script, you can automate formatting tasks in Google Docs. This script is a great starting point for customizing your document automation further.

Do you have other formatting challenges? Let me know in the comments, and I’d be happy to help! 🚀