0

I am trying to change the background color of only the selected text in a Google Doc. I took most of the code below from this answer. The problem is, it highlights the entire paragraph, rather than the selected text. What needs to be changed?

function highlightSelected() {
   // Try to get the current selection in the document. If this fails (e.g.,
   // because nothing is selected), show an alert and exit the function.
   var selection = DocumentApp.getActiveDocument().getSelection();
   if (!selection) {
      DocumentApp.getUi().alert('Cannot find a selection in the document.');
      return;
   }

   var selectedElements = selection.getSelectedElements();
   for (var i = 0; i < selectedElements.length; ++i) {
      var selectedElement = selectedElements[i];

      // Only modify elements that can be edited as text; skip images and other
      // non-text elements.
      var text = selectedElement.getElement().editAsText();
      text.setBackgroundColor('#00FFFF');

   }
}
Adam_G
  • 7,337
  • 20
  • 86
  • 148

1 Answers1

1

Try this out

function highlightSelected() {
  var doc  = DocumentApp.openById('<your document id');
  var selection  = 'highlight me text';
  var highlightStyle = {};
  highlightStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = '#FF0000';
  var paras = doc.getParagraphs();
  var textLocation = {};
  var i;

  for (i=0; i<paras.length; ++i) {
    textLocation = paras[i].findText(selection );
    if (textLocation != null && textLocation.getStartOffset() != -1) {
      textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
    }
  }
}
Nikko J.
  • 5,319
  • 1
  • 5
  • 14
QueenBee
  • 107
  • 1
  • 9