I’m working with a Google Apps Script that highlights text in a document:
const searchResult = document.findText(searchTerm);
if (searchResult) {
const selection = document.newRange();
selection.addElement(searchResult.getElement().asText(),
searchResult.getStartOffset(),
searchResult.getEndOffsetInclusive())
document.setSelection(selection.build())
}
This code works perfectly for highlighting text. However, I need to remove the selection afterwards so nothing appears highlighted (like when a user clicks elsewhere in the doc).
What I’ve attempted
Tried passing null:
document.setSelection(null);
This throws an error that the range parameter cannot be null.
Also tried creating an empty range:
document.setSelection(document.newRange().build());
This results in:
Exception: Invalid argument: range at clearSelection
I checked the Apps Script documentation but couldn’t find a solution. It seems odd that getSelection returns null when nothing is selected, but setSelection won’t accept null to clear the selection.
I move the cursor to the document end instead of the beginning - works way better when users are editing further down the page. Try this:
const body = document.getBody();
const lastChild = body.getChild(body.getNumChildren() - 1);
const endPos = document.newPosition(lastChild, lastChild.getText().length);
document.setCursor(endPos);
No highlighting sticks around and the cursor lands at the bottom where it feels natural.
Had the same problem when I built an automated review system. Google Docs selections don’t work like regular web selections. Don’t try clearing the selection directly - instead, make a new range at the document’s start and set that as your selection:
const firstElement = document.getBody().getChild(0);
if (firstElement.getType() === DocumentApp.ElementType.PARAGRAPH) {
const startRange = document.newRange();
startRange.addElement(firstElement.asParagraph(), 0, 0);
document.setSelection(startRange.build());
}
This moves the selection to position zero and kills any visible highlighting. Works reliably across different document structures.
Hit this same problem last month building a document processing script. Don’t try to clear the selection completely - just set it to a cursor position instead. This worked for me by placing the cursor right after the found text:
const position = document.newPosition(searchResult.getElement().asText(), searchResult.getEndOffsetInclusive() + 1);
document.setCursor(position);
This kills the highlight by turning the range selection into a cursor. Text stops being highlighted and acts like the user clicked somewhere else. Just watch out for cases where the offset goes past the element length.