Daisuki Honey
Daisuki Honey

Reputation: 157

How can I move the cursor to the beginning of the document with Google Apps Script for Docs?

I am writing a script of Google Apps Script with my Google Document and wondering how to move the cursor to the very beginning of the document. What I was trying to do at the end is just replace the first line with some string.

Upvotes: 5

Views: 4387

Answers (1)

Serge insas
Serge insas

Reputation: 46794

This is very simple, you can use the setCursor() method documented here.

Example code :

function setCursorToStart() {
 var doc = DocumentApp.getActiveDocument();
 var paragraph = doc.getBody().getChild(0);
 var position = doc.newPosition(paragraph.getChild(0), 0);
 doc.setCursor(position);
}

This will set the cursor position to the start of your document but in your question you say you want to insert some data at this position, then the actual cursor position is irrelevant, you can insert a string there without necessarily moving the cursor . Example code :

function insertTextOnTop() {
  var doc = DocumentApp.getActiveDocument();
  var top = doc.getBody().getChild(0);
  top.asParagraph().insertText(0,'text to insert');
  doc.saveAndClose();
}

Upvotes: 8

Related Questions