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');
}
}