I'm writing an app script and I'm trying to make a function that highlights a particular piece of text. The result of the code is that I'm highlighting the entire line instead of just the text.
Before:
After:
What I want:
Here is my code:
function myFun4(){
var selection = DocumentApp.getActiveDocument().getSelection();
if(selection){
var el = selection.getRangeElements();
Logger.log(el[0].getElement().getAttributes());
var el0 = el[0].getElement();
Logger.log(el0.asText());
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.BOLD] = true;
highlightStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = '#FFFF00';
el0.setAttributes(highlightStyle);
}
}
I believe your goal as follows.
In this case, how about the following modification?
When you use this script, please select a text on Google Document and run the script.
function myFun4(){
var selection = DocumentApp.getActiveDocument().getSelection();
if(selection){
selection.getRangeElements().forEach(e => {
var range = [e.getStartOffset(), e.getEndOffsetInclusive()];
e.getElement().asText()
.setBackgroundColor(...range, '#FFFF00')
.setBold(...range, true);
});
}
}
In this modification, the background color and bold are reflected to the selected text using the methods of setBackgroundColor(startOffset, endOffsetInclusive, color)
and setBold(startOffset, endOffsetInclusive, bold)
.
In your script, the style of paragraph is changed. I thought that this might be the reason of your issue.