5

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.

Rubén
  • 34,714
  • 9
  • 70
  • 166
user2846736
  • 71
  • 1
  • 4

2 Answers2

6

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)
bruce
  • 1,408
  • 11
  • 33
2

Thanks to bruce's answer I was able to figure out a solution to this problem, however if I was inserting Elements from another document I needed to actually find the index of the parent of the found text, as the found text was just a Text element inside of a Paragraph Element. So, I needed to find the index of the Paragraph Element, and then insert the new elements in relation to that Paragraph.

The code looks like this:

  var foundTag = body.findText(searchPattern);
  if (foundTag != null) {
    var tagElement = foundTag.getElement();
    var parent = tagElement.getParent();
    var insertPoint = parent.getParent().getChildIndex(parent);
    var otherBody = DocumentApp.openById(requirementsId).getActiveSection();
    var totalElements = otherBody.getNumChildren();

    for( var j = 0; j < totalElements; ++j ) {
    ... then same insertCode from the question above ...
      insertPoint++;
    }
stmcallister
  • 1,682
  • 1
  • 12
  • 21
  • When there is an inline image before the findText location, it gives the child index of the paragraph before the image, not after the image like needed. Is there a workaround? – John Targaryen Jun 03 '15 at 00:12