Enhancing Google Docs with Apps Script: Formatting Selected Text with Bold

Google Apps Script is a powerful tool for automating and enhancing Google Docs functionality. One common use case is modifying selected text dynamically, such as making it bold. In this blog post, we’ll explore a function that takes a user’s text selection in a Google Document and applies bold formatting while handling partial selections.


Understanding the myFun9 Function

The myFun9 function is designed to:

  1. Capture the current text selection in a Google Docs document.
  2. Loop through selected elements, checking if they are editable text.
  3. Apply bold formatting based on whether the selection is partial or full.
  4. Display an alert with the selected text for user feedback.

Let’s break it down step by step.


Step-by-Step Code Explanation

Here’s the full function:

function myFun9() {
var selection = DocumentApp.getActiveDocument().getSelection();
var output = ""; // Initialize output correctly
if (selection) {
var el = selection.getRangeElements();
var ui = DocumentApp.getUi();

for (var x = 0; x < el.length; x++) {
var element = el[x].getElement();
if (element.editAsText) { // Ensure it's a text element
var holder = element.editAsText();
output += holder.getText(); // Append selected text

if (el[x].isPartial()) { // Check if selection is partial
holder.setBold(el[x].getStartOffset(), el[x].getEndOffsetInclusive(), true);
} else {
holder.setBold(true); // Apply bold to the whole text
}
}
}

ui.alert('Selected text: ' + output);
} else {
DocumentApp.getUi().alert('No text selected.');
}
}

How It Works

  1. Retrieving the SelectionjavascriptCopyEditvar selection = DocumentApp.getActiveDocument().getSelection();
    • This grabs the user’s selection in the document.
    • If no text is selected, the script skips further processing.
  2. Looping Through Selected ElementsjavascriptCopyEditvar el = selection.getRangeElements(); for (var x = 0; x < el.length; x++) {
    • The getRangeElements() method extracts all selected elements, allowing us to iterate through them.
  3. Checking if the Element is Editable TextjavascriptCopyEditvar element = el[x].getElement(); if (element.editAsText) {
    • Some elements in Google Docs (like images or tables) are not text elements.
    • editAsText() ensures we only modify text.
  4. Extracting Text from the SelectionjavascriptCopyEditvar holder = element.editAsText(); output += holder.getText();
    • The getText() method extracts text from the element and appends it to output for display.
  5. Applying Bold Formatting
    • If the selection is partial:javascriptCopyEditif (el[x].isPartial()) { holder.setBold(el[x].getStartOffset(), el[x].getEndOffsetInclusive(), true);
      • getStartOffset() and getEndOffsetInclusive() ensure bolding only the selected portion.
    • If the whole element is selected:javascriptCopyEdit} else { holder.setBold(true);
      • The entire element is bolded.
  6. Displaying the Selected TextjavascriptCopyEditui.alert('Selected text: ' + output);
    • The script alerts the user with the text they selected.

Common Issues & Fixes

Issue: “Only the first element gets bold”
👉 Fix: Ensure the loop iterates over all selected elements and correctly applies setBold().

Issue: “TypeError: Cannot read properties of undefined”
👉 Fix: Initialize output = "" before appending text.

Issue: “No definition found for editAsText
👉 Fix: Use if (element.editAsText) instead of checking it as a property.


Use Cases

🚀 Batch Formatting: Quickly bold multiple sections of text.
📑 Custom Document Processing: Enhance formatting automation.
🎯 User-Friendly Interactions: Alerts help users confirm selections.