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();
// Change the background color of the selected part of the element, or the
// full element if it's completely selected.
if (selectedElement.isPartial()) {
text.setColor(selectedElement.getStartOffset(),
selectedElement.getEndOffsetInclusive(), '#69359c');
}
}
}
The above text takes a selection inside of a Google Doc and changes it to the hex code #69359c (a dark purple). I have searched many websites, many gits, and asked many friends for help with my project.
My end project is this:
If anyone can help me it would be highly appreciated.
I just found this question and am happy to provide some working code from my Rainbow Font Google Docs add-on (Magic Rainbow Unicorns).
The first problem is that you need to set the foreground color on the text, and the second is that the code above only allows for partial paragraph selections.
For whole selections use this code:
var elementText = element.editAsText();
if (elementText) {
var paragraph = elementText.getText();
for (var j = 0; j < paragraph.length; j++) {
elementText.setForegroundColor(j, j, getNextRainbowColour(...));
}
}
For partial selections, I used this:
var elementText = element.asText();
var startIndex = element.getStartOffset();
var endIndex = elements.getEndOffsetInclusive();
for (var j = startIndex; j < endIndex+1; j++) {
elementText.setForegroundColor(j, j, getNextRainbowColour(...));
}