wepli23
wepli23

Reputation: 87

rangeElement.getStartOffset() is always -1

I am trying to get the position of different rangeElements in a Google document. But the result is always -1.

What I did: I put every heading of my document into its own rangeElement, so that is has its own id. With this id I want to retrieve the content and position later on in a different function.

var doc = DocumentApp.getActiveDocument();
var paragraphs = doc.getBody().getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
if (paragraphs[i].getType() == DocumentApp.ElementType.PARAGRAPH) {
    var heading = paragraphs[i].asParagraph().getHeading();
    //get only headings
    if (heading == DocumentApp.ParagraphHeading.HEADING1) {
    var title = paragraphs[i].asParagraph().asText().getText();
    if (title != "") {
        //put every headings into its own range, so it has its own id
        var rangeBuilder = doc.newRange().addElement(paragraphs[i]);
        var id = doc.addNamedRange('toc', rangeBuilder.build()).getId();
        // check offset and text of the rangeElement
        var offset = doc.getNamedRangeById(id).getRange().getRangeElements()[0].getStartOffset();
        var text = doc.getNamedRangeById(id).getRange().getRangeElements()[0].getStartOffset();
    }
}

In this example the output of text is always the right heading. So the content of the rangeElement seems to be correct. But the output of offset is always -1.

What I want to do next is that:

doc.setCursor(doc.newPosition(rangeElement.getElement(), rangeElement.getStartOffset()));

But that does not work with a StartOffset of -1.

Upvotes: 1

Views: 769

Answers (1)

Cooper
Cooper

Reputation: 64032

The Apps Scripts Documentation says: getStartOffset() Gets the position of the start of a partial range within the range element. If the element is a Text element and isPartial() returns true, the offset is the number of characters before the start of the range (that is, the index of the first character in the range); in any other case, this method returns -1.

Reference:

If you want to find the offset some piece of text in all of the documents text then try this.

function findTextOffset(s){
  var s=s || 'Monster';//debug default
  var doc=DocumentApp.getActiveDocument();
  var text=doc.getBody().getText();
  var offset=text.indexOf(s);
  var ui=HtmlService.createHtmlOutput(Utilities.formatString('Find: %s Text: %s Offset: %s',s, text, offset));
  DocumentApp.getUi().showModelessDialog(ui, 'Text Offset');
}

Upvotes: 1

Related Questions