0
votes

I’m having a problem with document.newPosition(element,offest). According to the API spec., https://developers.google.com/apps-script/reference/document/document#newPosition(Element,Integer),

the element that will contain the new Position; this must be either a Text element or a container element like Paragraph

I’ve tried both .getText and .editAsText to get a Text element:

  var d=DocumentApp.getActiveDocument();
  var t1=d.getBody().editAsText();
  var t2=d.getBody().getText();

and then

  var position = d.newPosition(t1,ix);
  var position = d.newPosition(t2,ix);

where ix is an integer that is definitely within the text size.

Using t1 (editAsText), I get :

We're sorry, a server error occurred. Please wait a bit and try again. (line 32, file "testcode”)

where line 32 is the “var position=... line.

Using t2 (getText), I get:

Cannot find method newPosition(string,number). (line 32, file "testcode")

Does anyone know how to get a newPosition with a text element?

1

1 Answers

0
votes

From the docs it would appear that your method should work, but as you know, it throws errors. You do have several other options to choose from according to what your document looks like.

Remember that newPosition() creates a position relative to a specific element - either a text element or a container element. Since getting the entire body as a text element throws an error, just use the body as a container element.

var d=DocumentApp.getActiveDocument();
var body = d.getBody();
var ix = 2;

// this will get the position of the 2nd element in body container
var position = d.newPosition(body,ix);

Option two could be to grab a child element from the body:

var child = body.getChild(2);

// if the 2nd child is a paragraph, the new position will be at the end of the paragraph
// any number greater than one would actually reference the position of the next 
// child and throw an error.
var position = d.newPosition(child, 1)

.

What it looks like you are trying to do is to put the cursor x spaces in a particular element. In that case, you would need to get that specific element. Probably a text element within a paragraph within the body.

var body = d.getBody();
var parTwo = body.getChild(2);
var childTwo = parTwo.getChild(0);
var position = d.newPosition(childTwo, ix);