Search code examples
google-apps-scriptgoogle-docs

How can you make the entire google docs document un-highlighted? (Google Apps Script)


I am making a program that will show you the most commonly used words in your Google Docs document and then highlight them. I want to have a menu button that, when clicked, will un-highlight everything that is currently highlighted.

I couldn't find anybody who was doing something similar so I tried this:

function onOpen() {
  var ui = DocumentApp.getUi();

  ui.createMenu("Extra Tools")
      .addItem('Clear Highlights', 'clear')
      )
  
  .addToUi();
}

function clear()
{
  var DocText = DocumentApp.getActiveDocument().getBody().getText();
  DocText.getElement().asText.setBackgroundColor("#FFFFFF");
}

but it didn't work, giving me the error "TypeError: Cannot find function getElement in object "

Is there a way to set the highlight/background color of the whole document to white/transparent?


Solution

  • Try this:

    function clearHighLight() {
      var bgcolor='#ffffff';//white
      var doc=DocumentApp.getActiveDocument();
      var rangeBuilder=doc.newRange();
      var bdy=doc.getBody();
      var numCh=bdy.getNumChildren();
      for (var i=0;i<numCh;i++) {
        var child=bdy.getChild(i);//collect all range elements
        var all=rangeBuilder.addElement(child);
      }
      doc.setSelection(all);
      var selectedElements = all.getRangeElements();
      for(var i=0;i<selectedElements.length;i++) {
        var selElem = selectedElements[i];
        var el = selElem.getElement();
        var isPartial = selElem.isPartial();
        if(isPartial) {
          var selStart = selElem.getStartOffset();
          var selEnd = selElem.getEndOffsetInclusive();
          el.asText().setBackgroundColor(selStart, selEnd, bgcolor)      
        }else {
          var selStart = selElem.getStartOffset();
          var selEnd = selElem.getEndOffsetInclusive();
          el.asText().setBackgroundColor(bgcolor);
        }
      }
      var rg=doc.newRange();
      rg.addElement(bdy.getChild(0));//child zero normally has nothing in it
      doc.setSelection(rg.build());
    }