giorgio79
giorgio79

Reputation: 4189

Google Apps Script: Finding text and setting cursor to found text

I would like to setCursor to the location that is returned by findText.

Here is what I am trying:

    var position = doc.newPosition(foundElement.getElement(), foundElement.getStartOffset());
    doc.setCursor(position);

But, the cursor does not move. Even with the simple examples like

 //setting cursor at the beginning of the doc
 var paragraph = doc.getBody().getChild(0);
 var position = doc.newPosition(paragraph.getChild(0), 0);
 doc.setCursor(position);

findText returns a rangelement, while document.setCursor expects a position. How do I go from rangeelement to position? :)

This got me halfway to the solution Finding text (multiple times) and highlighting

Upvotes: 0

Views: 2477

Answers (1)

KRR
KRR

Reputation: 4907

Tried this code and it is perfectly setting the cursor in the beginning of the found text.

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var paragraph = doc.getBody().getChild(0);
  var foundElement = doc.getBody().findText("text");
  var position = doc.newPosition(foundElement.getElement(), foundElement.getStartOffset());
    doc.setCursor(position);
}

Hope that helps!

Upvotes: 3

Related Questions