Search code examples
javascriptgoogle-apps-scriptgoogle-docs

Google App Scripts Highlight Selected Text


I'm writing an app script and I'm trying to make a function that highlights a particular piece of text. The result of the code is that I'm highlighting the entire line instead of just the text.

Before:

enter image description here

After:

enter image description here

What I want:

enter image description here

Here is my code:

function myFun4(){
  var selection = DocumentApp.getActiveDocument().getSelection();
  if(selection){
    var el = selection.getRangeElements();
    Logger.log(el[0].getElement().getAttributes());
    var el0 = el[0].getElement();
    Logger.log(el0.asText());
    var highlightStyle = {};
    highlightStyle[DocumentApp.Attribute.BOLD] = true;
    highlightStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = '#FFFF00';
    el0.setAttributes(highlightStyle);   
  }
}

Solution

  • I believe your goal as follows.

    • You want to highlight the selected text on Google Document.

    In this case, how about the following modification?

    Modified script:

    When you use this script, please select a text on Google Document and run the script.

    function myFun4(){
      var selection = DocumentApp.getActiveDocument().getSelection();
      if(selection){
        selection.getRangeElements().forEach(e => {
          var range = [e.getStartOffset(), e.getEndOffsetInclusive()];
          e.getElement().asText()
            .setBackgroundColor(...range, '#FFFF00')
            .setBold(...range, true);
        });
      }
    }
    
    • In this modification, the background color and bold are reflected to the selected text using the methods of setBackgroundColor(startOffset, endOffsetInclusive, color) and setBold(startOffset, endOffsetInclusive, bold).

    • In your script, the style of paragraph is changed. I thought that this might be the reason of your issue.

    References: