Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
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);   
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

  • setBackgroundColor(startOffset, endOffsetInclusive, color)
  • setBold(startOffset, endOffsetInclusive, bold)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!