Reputation: 486
The problem is to erase all content paragraphs, images, tables or whatever after some specific text ('#PLACEHOLDER#' in my case). Do I need to loop through all or can I clear everything just after getting the position of range?
var body = somedoc.getBody();
var range = body.findText("#PLACEHOLDER#");
var ele = range.getElement();
if (ele.getParent().getParent().getType() === DocumentApp.ElementType.BODY_SECTION) {
var offset = body.getChildIndex(ele.getParent());
}
Can I add something like body.delteText(offset + 1)
or body.setText('',offset + 1)
?
Upvotes: 1
Views: 1302
Reputation: 201378
#PLACEHOLDER#
in the Google Document.If my understanding is correct, how about this modification? Please think of this as just one of several answers.
In this pattern, Document service is used.
Please modify as follows. In this modification, the script in the if statement is modified.
From:var offset = body.getChildIndex(ele.getParent());
To:
var offset = body.getChildIndex(ele.getParent());
// Retrieve total number of children in the body.
var numChildren = body.getNumChildren();
// If the text of the last paragraph is cleared.
body.getChild(numChildren - 1).asParagraph().editAsText().setText("");
// The children from offset to the child before the last paragraph are removed.
for (var i = numChildren - 2; i > offset; i--) {
body.removeChild(body.getChild(i));
}
#PLACEHOLDER#
is not removed. If you want to also remove the paragraph of #PLACEHOLDER#
, please modify as follows.
for (var i = numChildren - 2; i > offset; i--) {
for (var i = numChildren - 2; i >= offset; i--) {
In this pattern, Google Docs API is used. When you use this script, please enable Docs API at Advanced Google services. In this case, the result from body.findText("#PLACEHOLDER#")
is used and the for loop for removing children is not used.
Please modify as follows. In this modification, the script in the if statement is modified.
From:var offset = body.getChildIndex(ele.getParent());
To:
var offset = body.getChildIndex(ele.getParent());
// Retrieve document.
var content = Docs.Documents.get(somedoc.getId()).body.content;
// Create request body.
var startIndex = content[offset + 1].paragraph.elements[0].endIndex;
var endIndex = content[content.length - 1].paragraph.elements[0].endIndex - 1;
var resource = {requests: [{deleteContentRange: {range: {startIndex: startIndex, endIndex: endIndex}}}]};
// Update document.
Docs.Documents.batchUpdate(resource, somedoc.getId());
#PLACEHOLDER#
is not removed. If you want to also remove the paragraph of #PLACEHOLDER#
, please modify as follows.
content[offset + 1].paragraph.elements[0].endIndex
content[offset].paragraph.elements[0].endIndex
If I misunderstood your question and this was not the direction you want, I apologize.
Upvotes: 1