Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child index of findtext in google API script

My goal is to replace a piece of text in a Google Drive document with the contents of another document.

I have been able to insert the document at a certain position in the other document, but I'm having trouble determining the child index of the piece of text I want to replace. Here is what I have so far:

function replace(docId, requirementsId) {

var body = DocumentApp.openById(docId).getActiveSection();
var searchResult = body.findText("<<requirementsBody>>");
var pos = searchResult.?? // Here I would need to determine the position of the searchResult, to use it in the insertParagraph function below

var otherBody = DocumentApp.openById(requirementsId).getActiveSection();
var totalElements = otherBody.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var element = otherBody.getChild(j).copy();
  var type = element.getType();
  if( type == DocumentApp.ElementType.PARAGRAPH ) {
      body.insertParagraph(pos,element);   
  } else if( type == DocumentApp.ElementType.TABLE ) {
    body.insertTable(pos,element);
  } else if( type == DocumentApp.ElementType.LIST_ITEM ) {
    body.insertListItem(pos,element);
  } else {
    throw new Error("According to the doc this type couldn't appear in the body: "+type);
  }
}


};

Any assistance would be greatly appreciated.

like image 258
user2846736 Avatar asked Oct 04 '13 13:10

user2846736


Video Answer


1 Answers

findText()

returns a RangeElement.

You can use

var r = rangeElement.getElement()

to get the element containing the found text.

To get its childIndex you can use

r.getParent().getChildIndex(r)
like image 192
bruce Avatar answered Nov 09 '22 15:11

bruce