I'm trying to iterate over every element in the document, acquiring the start/end positions of each paragraph. But it keeps return -1. Any ideas what I'm doing wrong?
var body = doc.getBody();
var elements = body.getNumChildren();
for( var i=0;i<elements;i++) {
var element = body.getChild(i).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ){
var text = element.asParagraph().getText();
var range = element.asParagraph().findElement(DocumentApp.ElementType.PARAGRAPH);
var start = range.getStartOffset();
var finish = range.getEndOffsetInclusive();
According to the official docs, the
Rangeclass is only accessible if there is a selection by the current user on the page. So, you can get the script to work, but it requires some user input rather than running on a blank document.The offsets check the position of the selection against the last element. If it is text, then it will return the index. If not (such as a page break or image) it will return -1.
Adding a simple
onOpenevent will allow you to run the script from a custom menu for testing: