2013-10-04 6 views
5

私の目標は、Googleドライブのドキュメントのテキストを別のドキュメントのコンテンツで置き換えることです。GoogleのAPIスクリプトでfindtextの子インデックスを取得

他のドキュメントの特定の位置にドキュメントを挿入できましたが、置換するテキストの子インデックスを特定できませんでした。これまで私が持っているものは次のとおりです。

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); 
    } 
} 


}; 

ご協力いただければ幸いです。

答えて

5

findText()

はRangeElementを返します。

あなたが見つかりましたテキストを含む要素を取得するために

var r = rangeElement.getElement()

を使用することができます。私は実際にインデックスを見つけるために必要な別のドキュメントから要素を挿入した場合

そのchildIndexにを取得するには、しかし、私はこの問題に対する解決策を見つけ出すことができたブルースの答えに

r.getParent().getChildIndex(r) 
2

感謝を使用することができます発見されたテキストは、段落要素内の単なるテキスト要素であったため、発見されたテキストの親の一部であった。だから、私は段落要素のインデックスを見つけ、その段落に関連して新しい要素を挿入する必要がありました。

コードは次のようになります。必要なよう

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++; 
    } 
+0

FINDTEXT場所の前にインライン画像があり、それがない画像の後に、画像前の段落の子のインデックスを提供します。回避策はありますか? –